Discord py | Get message by ID - python

I'm working on a giveaway system for my discord bot.
I save the end time for running giveaways in a mysql database and when the end time equals the current time the bot calls a function to end the giveaway.
In the database I store the message-, channel- and server ID. Now the question.
How do I get the discord.Message from the ID?
I tried following but this doesn't seem to work:
giveaway_msg = bot.fetch_message(db_giveaway_message_ID)
db_giveaway_message_ID is the Message ID (904081961583251456)
EDIT
Current Code (still not working)
async def giveaway_end(giveaway_db_fetch):
print('Giveaway End startet')
db_giveaway_message_ID = giveaway_db_fetch[4]
db_giveaway_starter = giveaway_db_fetch[3]
fb_giveaway_channel_ID = giveaway_db_fetch[5]
db_giveaway_price = giveaway_db_fetch[1]
print(db_giveaway_message_ID)
giveaway_msg_channel = await bot.get_channel(fb_giveaway_channel_ID)
print(f'Giveaway Message Channel = {giveaway_msg_channel.name}')
giveaway_msg = await giveaway_msg_channel.fetch_message(db_giveaway_message_ID)
print(f'Message found: {giveaway_msg.id}')
It does print the messageID but nothing more happens. -no error-

Remember that you can't use bot.fetch_message, because when you want to fetch the message you have to call the channel (where the message was sent), the member (that sent this message) or context if it's used in a command.
Also, your current code works as expected (you wanted it to print the message-id). You properly fetched the discord.Message you just have to do something with it, other than only printing the id.
Fetch message:
giveaway_msg_channel = bot.get_channel(fb_giveaway_channel_ID)
giveaway_msg = await giveaway_msg_channel.fetch_message(db_giveaway_message_ID)
If you want to get the message content then:
print(f'Message found: {giveaway_msg.content}')
or author of the message:
print(f'Message found: {giveaway_msg.author}')
Check discord.Message in documentation

Related

how to specify if the message was from group or private in python telegram bot

Here is my code:
# 1st method
if chat.type == 'supergroup':
# Check if the bot's name was mentioned in the message
# if bot_name in message_text:
# Generate a response to the question
response_text = generate_response(message_text)
update.message.reply_text(response_text)
elif chat.type == 'private':
# Generate a response to the question
response_text = generate_response(message_text)
update.message.reply_text(response_text)
The 'private' is working fine if the message was sent in private chat but if it was send from the group the bot was not able to pick the message. The bot was also in the group.
I tried:
# 2nd method
if chat.id < 0:
# 3rd method
if message.chat.type in ["group", "supergroup"]:
to know if the message coming from the group but no luck.
Only the private one is working.
By default, bots don't see all messages that are written in group chats. Please have a look at this FAQ entry in the official Telegram docs for more info.

How to send when an event has ended in discord.py

I am trying to get an output like this, in which it tells when the message was sent
I successfully got when a message was sent
emb = discord.Embed(title=f"**{title}**", description=f"<:854745395314163784:910908229897297940> Ends in {lenght}")
emb.set_thumbnail(url='https://images-ext-2.discordapp.net/external/D14-NqrYBiv91a8nM8tVD4b0SuN-CAUlmooEq0dtWsM/https/kaj.gg/r/kq902alos9a.png?width=80&height=80')
emb.set_footer(text = f"{winners} Winner")
msg_2 = await ctx.send(embed=emb)
await msg_2.add_reaction(emoji)
id = msg_2.id
created = msg_2.created_at
print(created)
but I cant figure out how to return a message like "Ended a Few seconds ago" or "Ended few hours ago"
The example you sent uses Discord's built-in timestamp format, outlined here. You can obtain a Unix timestamp by using datetime's timestamp() function on msg_2.created_at, something like this for your example:
f"<t:{int(msg_2.created_at.replace(tzinfo=datetime.timezone.utc).timestamp())}:R>"
You can then include that string in a message normally.

Webhook status code 400: {"embeds": ["Must be 10 or fewer in length."]}

I´m developing a bot that sends messages to the discord channel every second, however when I run the program and only sent 10 messages and after only print [1/1] Webhook status code 400: {"embeds": ["Must be 10 or fewer in length."]}. I don't find why is this happening, I'm using discord_webhook library and python to do this. Here is my code
async def __scrape_api(session, pid):
async with session.get(API_URL + pid) as response:
data = await response.json()
print(f"scrape {data}")
if not __search_product(pid):
name = data["name"]
image_url = data['skus'][0]['image']
for size in data['skus']:
if size['available']:
print("sent")
message = DiscordEmbed(title=f'{name}', url=f'{PRODUCT_URL_0}{size["sku"]}{PRODUCT_URL_1}',
description=f'talla: {size["dimensions"]["Tallas Calzado"]}\nPrecio: {size["bestPriceFormated"]}')
message.set_thumbnail(url=image_url)
message.set_timestamp()
webhook.add_embed(message)
response = webhook.execute()
time.sleep(1)
# save to database
__insert_new_product(pid, name, image_url, data['available'])
I found the solution for this after few minutes of taking a deeper look inside it's code. Basically each embed you send over is being held in the webhook object, once you made 10 requests with embeds then it gives you that error. All you have to do is:
webhook.execute(remove_embeds=True)

Telethon: delete a message

I am trying to delete a message using telegram API and Telethon.
Here is my code:
from telethon import InteractiveTelegramClient
from telethon.tl.types.input_peer_channel import InputPeerChannel
from telethon.tl.functions.messages.delete_messages import DeleteMessagesRequest
#...
total_count, messages, senders = client.get_message_history(
chat, limit=1)
msg = messages[0]
result = client.invoke(DeleteMessagesRequest([msg.id]))
But first of all nothing happens, and second, it doesn't look right, since msg.id is like 5 or 220 and it doesn't look like a unique number.
Here is the message:
msg: (message (ID: 0xc09bexxx) = (out=None, mentioned=None, media_unread=None, silent=None, post=True, id=5, from_id=None, to_id=(peerChannel (ID: 0xbdddexxx) = (channel_id=1234)), fwd_from=None, via_bot_id=None, reply_to_msg_id=None, date=2017-06-14 14:39:23, message=test33, media=None, reply_markup=None, entities=None, views=1, edit_date=None))
I also tried with the hex number 0xc09bexxx but that gives an exception.
So how can I delete a message in a channel?
So far I looked at this github issue to get started with the delete message. My guess is that maybe the following import is not the right one and I should import the version in the Channels package, which gets a channel id and a message id?
from telethon.tl.functions.messages.delete_messages import DeleteMessagesRequest
Using the other delete from channels package I was able to get the delete message working, but I am still curious to know how to get the delete from messages.delete_messages working.
from telethon.tl.functions.channels.delete_messages import DeleteMessagesRequest
channel = InputPeerChannel(channel_id, access_hash)
result = client.invoke(DeleteMessagesRequest(channel, [msg.id]))
and it will delete the message from the channel.
from telethon import TelegramClient
client = TelegramClient('cookie', '123', 'XXX')
id_group = -1001231231231
id_message = 3
await client.delete_messages(entity=id_group, message_ids=[id_message])
For example if u want to obtain all the msgs-ids in the channel and after of it delete all messages... this code works to me:
from telethon import TelegramClient
client = TelegramClient('cookiename', Apiid, 'api_hash')
id_group = -XXXX
async def getmsgs(client,id_group):
messagesid = []
async for message in client.iter_messages(id_group):
print(message.id)
messagesid.append(message.id)
return messagesid
async def delmsgs(client,id_group,list_msgs_id):
await client.delete_messages(entity=id_group, message_ids=list_msgs_id)
with client:
messages = client.loop.run_until_complete(getmsgs(client,id_group))
client.loop.run_until_complete(delmsgs(client,id_group,messages))

Telegram bot API: get message id to forward it

So, I need my bot to forward a message of a chat. But in order to do so, I need to get the id of the message I want to forward (it's an old message). How can I get the id of that message so I can send it?
This is the code I'm using
#bot.message_handler(func=lambda m: True)
def reply_ids(message):
cid = message.chat.id
bot.reply_to(message, "The message id is: " + str(message.message_id) + " This chat ID is: " + str(cid))
When receiving a message, the id will be in message.message_id, as documented here.
If it is a supergroup or a channel, you can get the message_id by clicking on the message (in telegram web ) then choosing copy message link. the link will be in this form "https://t.me/channel_name/message_id"
This solution is to find the message_id manually!!
Recently I've been working with callback queries from inline buttons. One things I noticed is that in order to reply to the exact message that had the buttons Telegram needs to know both message.chat_id and message.message_id. You can try with both. This is more a comment then an answer but I don't have enough reputation to comment.
UPDATE: Now, It's update.message.message_id
Using python, if you have a CommandHandler() you can read the chat_id and message_id like so:
https://stackoverflow.com/a/72433953/1000741

Categories