editing messages with discord.py - python-3.x

I'm trying to edit my bots sent messages, but I'm getting an error
#client.command()
async def edit(ctx):
message = await ctx.send('testing')
time.sleep(0.3)
message.edit(content='v2')
Error:
RuntimeWarning: coroutine 'Message.edit' was never awaited
message.edit(content='v2')
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
And by the way, is there any way of editing a message by simply having the message ID?

time.sleep() is a blocking call, meaning that it pretty much screws up your script. What you'll instead want to use is await asyncio.sleep().
Also, edit() is a coroutine, so it needs to be awaited. Here is what your command should look like:
import asyncio # if you haven't already
#client.command()
async def edit(ctx):
message = await ctx.send('testing')
await asyncio.sleep(0.3)
await message.edit(content='v2')
To edit a message via ID, you'll need the channel that it came from:
#client.command()
async def edit(ctx, msg_id: int = None, channel: discord.TextChannel = None):
if not msg_id:
channel = client.get_channel(112233445566778899) # the message's channel
msg_id = 998877665544332211 # the message's id
elif not channel:
channel = ctx.channel
msg = await channel.fetch_message(msg_id)
await msg.edit(content="Some content!")
The usage for this command would be !edit 112233445566778899 #message-channel-origin assuming that the prefix is !, and don't bother using the channel argument if the message is in the channel you're executing the command in.
References:
Message.edit()
asyncio.sleep()
Messageable.fetch_message()

Related

D.py/rewrite - Confessions System

I made a confessions system but there’s some things that are wrong with it. How would I make it so when users want to type, they don’t have to put in *confess and they can just type whatever they want without needing to use a command? And how do I make a mod logs channel to log the deleted confessions with the author name, etc.?
import discord
from discord.ext import commands
class Confess(commands.Cog):
def __init__(self, client: discord.ext.commands.Bot):
self.client = client
#commands.command()
async def confess(self, ctx: commands.Context, *, message: str):
channel = self.client.get_channel(806649868314869760)
await ctx.message.delete()
embed = discord.Embed(title="Success", description=f"I've received your confession and sent it to the <#806649874379964487> channel!")
embed.set_footer(text="Confessions")
await ctx.send(embed=embed, delete_after=10)
channel = self.client.get_channel(806649874379964487)
embed = discord.Embed(title="Confession", description=f"{message}")
embed.set_footer(text="All confessions are anonymous.")
await channel.send(embed=embed)
def setup(client):
client.add_cog(Confess(client))
For the first question
If you want to use a "command" without actually using a command you could make an on_message event, check the id of the channel (like a confessions channel) and if it matches then do the thing
Example:
#commands.Cog.listener()
async def on_message(message):
if message.channel.id == some_channel_id_here:
channel = self.client.get_channel(806649868314869760)
await message.delete()
embed = discord.Embed(title="Success", description=f"I've received your confession and sent it to the <#806649874379964487> channel!")
embed.set_footer(text="Confessions")
await message.channel.send(embed=embed, delete_after=10)
channel = self.client.get_channel(806649874379964487)
embed = discord.Embed(title="Confession", description=f"{message}")
embed.set_footer(text="All confessions are anonymous.")
await channel.send(embed=embed)
For the second question
You can use get_channel again to get the log channel and post in there. (If you mean't on how to check if someone deleted a message/confession, use on_message_delete)
Example:
#commands.command()
async def confess(self, ctx: commands.Context, *, message: str):
channel = self.client.get_channel(806649868314869760)
log_channel = self.client.get_channel(log_channel_id)
await ctx.message.delete()
embed = discord.Embed(title="Success", description=f"I've received your confession and sent it to the <#806649874379964487> channel!")
embed.set_footer(text="Confessions")
await ctx.send(embed=embed, delete_after=10)
channel = self.client.get_channel(806649874379964487)
embed = discord.Embed(title="Confession", description=f"{message}")
embed.set_footer(text="All confessions are anonymous.")
await channel.send(embed=embed)
await logchannel.send("User confessed something!")

Discord.py running an async function on demand

I want to run the following async function at a certain time.
async def test(ctx):
channel = bot.get_channel(730099302130516058)
await channel.send('hello')
I am testing it with
asyncio.run(test(bot.get_context)). But when I run it I get 'NoneType' object has no attribute 'send' And I have tested this and it means channel is equal to none so it cant send the message as channel = "None".
Now when I do the following it works. But of course I have to run the command test
#bot.command()
async def test(ctx):
channel = bot.get_channel(730099302130516058)
await channel.send('hello')
I plan to use schedule to run it at the times I required but will still call the function in a similar way.
Is there a way to call an async function and pass ctx correctly?
Entire Code:
import discord
from discord.ext import commands
import asyncio
TOKEN = "Token Would Be Here"
bot = commands.Bot(command_prefix='+')
async def test(ctx):
channel = bot.get_channel(730099302130516058)
await channel.send('hello')
asyncio.run(test(bot.get_context))
bot.run(TOKEN)
bot.get_channel() is returning None because the bot has not yet connected, meaning it cannot see any channels. You need to add await bot.wait_until_ready(), which will force the bot to wait until it is connected before continuing.
You also don't need to pass ctx as you never use it.
discord.py also already has it's own event loop that you can use. You can add the coroutine to the loop using bot.loop.create_task().
from discord.ext import commands
TOKEN = "Token Would Be Here"
bot = commands.Bot(command_prefix='+')
async def test():
await bot.wait_until_ready()
channel = bot.get_channel(370935329353367568)
await channel.send('hello')
bot.loop.create_task(test())
bot.run(TOKEN)

How do I add a reaction emoji to the message the bot sends after doing the user's command?

I get this error: discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'Bot' object has no attribute 'message'--when trying to do await self.client.message.add_reaction(emoji).
I tried changing it to await ctx.message.add_reaction(emoji), and I realized that it reacted to the command the user sent rather than the bot's new message.
import discord
from discord.ext import commands
class MovieNight(commands.Cog):
"""Polls for Movie Night."""
def __init__(self, client):
self.client = client
#commands.command(aliases=['m'])
async def movie(self, ctx, year, *movie):
movie_title = ' '.join(movie[:-1])
await ctx.send(f"`{year}` - `{movie_title}` | **{movie[-1]}**")
emoji = '👎'
await self.client.message.add_reaction(emoji)
def setup(client):
client.add_cog(MovieNight(client))
self.client doesn't know about the message, the is stored as part of the invocation context:
await ctx.message.add_reaction(emoji)
Adding onto Patrick's answer here from what you said in the comment.
await self.client.message.add_reaction(emoji) won't work because the bot doesn't know what message you're referring to, and client doesn't have an attribute called message.
Adding reactions requires a discord.Message object, which in your case can be either the command that the user executed (e.g. !movie 2020 movie title) which you can retrieve via ctx.message, or a message which you're making the bot send.
If you wanted to get the message object from the message that the bot sent, you can assign it to a variable:
msg = await ctx.send(f"`{year}` - `{movie_title}` | **{movie[-1]}**")
And this allows you to then add a reaction to it or access any other message attributes you would like:
emoji = '👎'
await msg.add_reaction(emoji)
References:
discord.Message
Message.add_reaction()
TextChannel.send() - Here you can see it returns the message that was sent

Deleting specific messages that was sent by the bot and sent by the user. Discord.py rewrite

I'm having a lot of trouble with discord.py rewrite and its migration. I looked at the migrating to v1.0 site and it said to put in message.delete() and so I did but I realised that wasn't working so I put in ctx aswell. But that put it to an error. There are two commands with this error at the moment.
I have already tried putting the message into a variable.
#client.command()
async def clear(ctx, amount=100):
message = ctx.message
channel = ctx.message.channel
messages = []
await ctx.channel.purge(limit=int(amount+1))
mymessage = await channel.send('Messages deleted')
await ctx.message.delete(mymessage)
#client.command()
async def verify(ctx, *, arg):
print(ctx.message.channel.id)
print(ctx.message.author)
if ctx.channel.id == 521645091098722305:
role = await ctx.guild.create_role(name=arg)
await ctx.message.author.add_roles(role)
mymessage = await ctx.send('Done! Welcome!')
await ctx.message.delete(mymessage)
await ctx.message.delete(ctx.message)
I expected the output to delete the message. For the clear one it deletes it and then gives it back. for the verify one it just keeps it as the same and shows the error:
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: TypeError: delete() takes 1 positional argument but 2 were given
Also my role giving verify sometimes goes 3 times. I have went into task manager and killed all of the python too but it still did that. Once when I was clearing it said Done! Welcome as well. If you can answer this question as well, I would be pleased! Thank you in advance.
Message.delete doesn't take any arguments. It's a method that you call on the message you want to delete. Change
await ctx.message.delete(mymessage)
await ctx.message.delete(ctx.message)
to
await mymessage.delete()
await ctx.message.delete()
#client.command(pass_context=True)
async def delete(ctx, arg):
arg1 = int(arg) + 1
await client.purge_from(ctx.message.channel, limit=arg1)
!delete 10 - delete the last 10 posts

How to send a message with discord.py from outside the event loop (i.e. from python-telegram-bot thread)?

I want to use make a bot that communicates between discord and telegram by using the libraries python-telegram-bot and discord.py (version 1.0.0). However the problem is that discord.py uses async functions and python-telegram-bot threading. With the code below, everything works fine for messages being posted in discord (the bot sends them correctly to telegram), however the other way around does not work (bot gets messages from telegram and sends it to discord). I previously had issues with syntax/runtime errors as I tried to run the discords channel.send function in a sync function (thus either returning only a generator object or complaining that I cannot use await in a sync function). However, at the same time the python-telegram-bot's MessageHandler needs a sync function so when giving him a async function Python complains that "await" was never called for the async function.
I now tried to use the async_to_sync method from asgiref library to run my async broadcastMsg from the MessageHandler, however the code still does not send the message to discord! It seems to call the function correctly but only until line print('I get to here'). No error is displayed and no message is poping up in discord. I guess it has something to do with the fact that I have to register the function as a task in the discord.py event loop, however registering is only working when it happens before botDiscord.run(TOKENDISCORD) has been executed which of course has to happen before.
So to boil my problem down to one question:
How am I able to interact with the discord.py event loop from another thread (which is from the telegram MessageHandler). Or if this is not possible: How can I send a message with discord.py without being within the discord.py event loop?
Thank you for your help
import asyncio
from asgiref.sync import async_to_sync
from telegram import Message as TMessage
from telegram.ext import (Updater,Filters,MessageHandler)
from discord.ext import commands
import discord
TChannelID = 'someTelegramChannelID'
DChannel = 'someDiscordChannelObject'
#%% define functions / commands
prefix = "?"
botDiscord = commands.Bot(command_prefix=prefix)
discordChannels = {}
async def broadcastMsg(medium,channel,message):
'''
Function to broadcast a message to all linked channels.
'''
if isinstance(message,TMessage):
fromMedium = 'Telegram'
author = message.from_user.username
channel = message.chat.title
content = message.text
elif isinstance(message,discord.Message):
fromMedium = 'Discord'
author = message.author
channel = message.channel.name
content = message.content
# check where message comes from
textToSend = '%s wrote on %s %s:\n%s'%(author,fromMedium,channel,content)
# go through channels and send the message
if 'telegram' in medium:
# transform channel to telegram chatID and send
updaterTelegram.bot.send_message(channel,textToSend)
elif 'discord' in medium:
print('I get to here')
await channel.send(textToSend)
print("I do not get there")
#botDiscord.event
async def on_message(message):
await broadcastMsg('telegram',TChannelID,message)
def on_TMessage(bot,update):
# check if this chat is already known, else save it
# get channels to send to and send message
async_to_sync(broadcastMsg)('discord',DChannel,update.message)
#%% initialize telegram and discord bot and run them
messageHandler = MessageHandler(Filters.text, on_TMessage)
updaterTelegram = Updater(token = TOKENTELEGRAM, request_kwargs={'read_timeout': 10, 'connect_timeout': 10})
updaterTelegram.dispatcher.add_handler(messageHandler)
updaterTelegram.start_polling()
botDiscord.run(TOKENDISCORD)
How can I send a message with discord.py without being within the discord.py event loop?
To safely schedule a coroutine from outside the event loop thread, use asyncio.run_coroutine_threadsafe:
_loop = asyncio.get_event_loop()
def on_TMessage(bot, update):
asyncio.run_coroutine_threadsafe(
broadcastMsg('discord', DChannel, update.message), _loop)
you can try split them to 2 separates *.py files.
t2d.py #telegram to discor
import subprocess
from telethon import TelegramClient, events, sync
api_id = '...'
api_hash = '...'
with TelegramClient('name', api_id, api_hash) as client:
#client.on(events.NewMessage()) #inside .NewMessage() you can put specific channel like: chats="test_channel"
async def handler(event):
print('test_channel raw text: ', event.raw_text) #this row is not necessary
msg = event.raw_text
subprocess.call(["python", "s2d.py", msg])
client.run_until_disconnected()
s2d.py #send to discord
import discord, sys
my_secret = '...'
clientdiscord = discord.Client()
#clientdiscord.event
async def on_ready():
#print('We have logged in as {0.user}'.format(clientdiscord)) #this row is not necessary
channel = clientdiscord.get_channel(123456789) # num of channel where you want to write message
msg = sys.argv[1] #grab message
msg = 's2d: ' + msg #only for test, you can delete this row
await channel.send(msg)
quit() # very important quit this bot
clientdiscord.run(my_secret)
It will be a little bit slower (subprocess will make delay), but very easy solution

Resources