What I want to achieve is that before I post new message via bot X I delete the previous messages that are posted by the same bot X. I'm looking at the method bot.delete_message but that requires message_id what means that I would need to store the id some-have locally. Is there any way around this? Like fetching bot own messages?
import python-telegram....
import time
current_message = None
def current_message_updater(new_message):
global current_message
# delete last message
if not current_message:
current_message.delete()
# send new message will return its message object,
# we assign it into current_message variable
new = bot.send_message(....., text=new_message)
current_message = new
# if all of this is happening in the same function
# you can do like this
def my handler():
message = bot.send_message(...., text="hi new user")
time.sleep(1)
message.delete()
another_one = bot.send_message(..., text="How are u?")
Related
I have created a bot in telegram and I wish to control it using python.
I am using python-telegram-bot API. What is the easiest way to figure out various ids using the python: bot id, chat id, message id, group id, channel id? Is there any readymade code available for this?
I suppose you have something like that
updater = Updater(TOKEN, use_context=True)
dp = updater.dispatcher
dp.add_handler(MessageHandler(Filters.text, echo))
with dispatcher.add_handler you associate a specific function to run when the bot receive a message (in this case only text messages due to Filters.text)
The function will be something like that:
def echo(update, context):
...
...
chat_id = update.message.chat_id
message_id = update.message.message_id
text = update.message.text
...
...
All the informations you need are inside the Update object, received by the Dispatcher, i extracted the more usefull, but there are a lot others. Check the documentation for more details.
import discord
import asyncio
from discord.ext import commands
client = commands.Bot(command_prefix=':')
token = ''
#client.event
async def on_ready():
print('BOT ONLINE')
#client.event
async def on_message(message):
channel = message.channel
if message.content.startswith('/'):
if message.content.startswith("/users"):
# FOR LOOP IN QUESTION ---------------
for guild in client.guilds:
for member in guild.members:
print(member) # or do whatever you wish with the member detail
client.run(token)
print("Bot Finished")
When I run this code all it returns is the bot name twice. The server has two members, myself and the bot. I need to iterate through every member of the server. What am I doing wrong?
You simply didn't enable intents.members
intents = discord.Intents.default()
intents.members = True
client = commands.Bot(command_prefix=":", intents=intents)
Also make sure to enable them in the developer portal
Reference:
intents.members
How to enable privileged intents
Im trying to create a fortnite API to give me all of the Leaked cosmetics with a discord bot and I just don't know where to get started! Could someone help! Thankyou
Here's an example of a simple bot that repeats what you say.
import discord # importing the discord.py library
from discord.ext import commands # extension of said library
# This defines the bot's command prefix and if the commands are case insensitive
bot = commands.Bot(command_prefix='-', case_insensitive='True')
#bot.event =
async def on_ready():
```
This is an event that prints to the console that the bot is online and ready to go.
```
print('Bot is ready!') # prints to console that the bot is ready.
#bot.command()
async def echo(ctx, *, msg):
```
This is a command that repeats what you say. Echo is the name. *, msg means that all the words listed after the command are repeated
```
await ctx.message.delete() # delete the command message the the user said
await ctx.send(msg) # say whatever the user wanted to say.
# bot token here. found in the discord developer website
bot.run(YOUR BOT'S TOKEN GOES HERE)
Here's an example of using a api inside a Cog
Necessary Imports:
from discord.ext import commands
from discord import Embed, Color
from aiohttp import ClientSession
from ast import literal_eval
A command to fetch random Chuck Norris jokes
#commands.command()
async def chuck(self, ctx):
ad = Embed(color=Color.dark_gold())
base = "https://api.chucknorris.io/jokes/random"
async with ClientSession() as session:
data = await get(session, base)
data = literal_eval(data)
ad.set_author(name="Chuck Norris",
icon_url="https://i.ibb.co/swZqcK7/norris.gif",
url=data['url'])
ad.description = data['value']
return await ctx.send(embed=ad)
If you're getting information from Fortnite, chances are they already have a Python Module on PyPi, alternatively you can look for a JSON endpoint and apply what I did above to get what you need.
I want my bot to send special sticker. I got it ID in logs after sending it to bot.
file_id "CAADAgADOQADfyesDlKEqOOd72VKAg"
This is what getUpdates give me
But if I try to send it, for example:
https://api.telegram.org/bot<token>/sendSticker?chat_id=<id>&file_id=CAADAgADOQADfyesDlKEqOOd72VKAg
It responds"Bad Request: there is no sticker in the request". This is the code and it obviously does nothing:
def stickinmyass(bot, update):
bot.send_sticker(chat_id=update.message.chat_id, file_id='CAADAgADOQADfyesDlKEqOOd72VKAg')
stickyass = MessageHandler(Filters.sticker, stickinmyass)
dispatcher.add_handler(stickyass)
j = updater.job_queue
The file_id needs to be passed as the sticker parameter for the sendSticker method.
https://api.telegram.org/bot<token>/sendSticker?chat_id=<id>&sticker=CAADAgADOQADfyesDlKEqOOd72VKAg
or
bot.send_sticker(chat_id=update.message.chat_id, sticker='CAADAgADOQADfyesDlKEqOOd72VKAg')
Say I have a class Messenger which is responsible for sending and receiving messages. Now I have a service that sends out requests and waits for responses via it, matching each pair with an id field in the message. In asyncio I would do:
class Service:
...
async def request(self, req):
new_id = self._gen_id()
req.id = new_id
fu = asyncio.Future()
self._requests[new_id] = fu
await self._messenger.send(req)
return await fu
def handle_response(self, res):
try:
fu = self._requests.pop(res.req_id)
except KeyError:
return
fu.set_result(res)
So I could send out multiple requests from different tasks, and in each task wait for the corresponding response. (And some messages may not have a corresponding response that are handled in another way.)
But how do I do this in Trio? Should I create an Event / Condition / Queue for each request and put the response in a predefined place?
If yes, which is the best for this scenario? Or there is another way to do this?
You could create a simple class that contains an Event and your result.
However, strictly speaking events are overkill because multiple tasks can wait on an event, which you don't need, so you should use trio.hazmat.wait_task_rescheduled. That also gives you a hook you can use to do something when the requesting task gets cancelled before receiving its reply.
http://trio.readthedocs.io/en/latest/reference-hazmat.html#low-level-blocking