Bypass on_command_error(ctx) and call variable of other function - python

In my case I want, that the messages of the ping command are deletet after a cooldown (5s) but the messages of the invite command should be not deleted. Is there a way to bypass the on_command_function without aborting the whole script or is it just easier to delete the messages locally?
And my other question: Is there a way to call the tmp variable, that was created in the ping command, in the on_command_completion function?
Here is a snippet:
#commands.command()
async def ping(self, ctx):
tmp = await ctx.send("Pong")
#commands.command()
async def invite(self, ctx):
invite = await ctx.channel.create_invite()
tmp = await ctx.send(invite)
#commands.Cog.listener()
async def on_command_completion(ctx):
await tmp.delete(delay=5.0)
await ctx.message.delete(delay=5.0)

Related

ERROR discord.ext.commands.bot Ignoring exception in command None discord.ext.commands.errors.CommandNotFound:

I am currently getting a CommandNotFound error when trying to call the command inside of this class. The message listener function is also not responding.
ERROR discord.ext.commands.bot Ignoring exception in command None
discord.ext.commands.errors.CommandNotFound: Command "black" is not found
I can't seem to see what I am doing wrong here...
class MyCog(commands.Cog):
def __init__(self, bot):
self.bot = bot
#commands.Cog.listener()
async def on_message(self, message):
if message.content == "hello":
await message.channel.send("HI!")
#commands.command()
async def black(self, ctx):
await ctx.send("White!")
bot.add_cog(MyCog(bot))
bot.run(BOT_TOKEN)
When you add a cog you need to await it.
await bot.add_cog(MyCog(bot))
To do that you'll need to change how you run your bot:
async def main():
async with bot:
await bot.add_cog(MyCog(bot))
await bot.start(BOT_TOKEN)
asyncio.run(main())
On another note, I would advise moving cogs into their own python file & directory. They're quite useful for organisation, but that is mostly lost when kept inside the main bot file.

TwitchIO not recognizing the command used before

I am having the problem where if I run my bot, the first time I use a command, link !hello it send 'Hello (and the author)' back. But when I then try it again, it doesn't respond anymore. It does print in the console from the event_message. Then if I use another command like the !test, it gives response, but when I try that then again, it doesn't, but if I try !hello then, it works again, but only for that 1 time, until I used another command first.
Here's the code:
class Bot(commands.Bot):
def __init__(self):
super().__init__(token='MYTOKEN', prefix='!', initial_channels=['MYCHANNEL'])
async def event_ready(self):
print(f'Logged in as | {self.nick}')
print(f'User id is | {self.user_id}')
async def event_message(self, message):
if message.echo:
return
print(message.content)
await self.handle_commands(message)
#commands.command()
async def hello(self, ctx: commands.Context):
await ctx.send(f'Hello {ctx.author.name}!')
#commands.command()
async def test(self, ctx: commands.Context):
await ctx.send(f'test {ctx.author.name}!')
bot = Bot()
bot.run()```
I asked them in the discord. Giving the bot account moderator fixed the problem, since before it couldn't send the same message again too fast after each other

Bot stopped working even though code is fine

This is my first time coding a discord bot and I have been following tutorials mainly but I wanted to make a unique game so I tried to make it myself. But after messing around with it for a while I realized that the only part of my code that works is the mcguccy is an idiot part none of the client. Command parts work.
import discord
from discord.ext import commands
client = commands.Bot(command_prefix='!')
#client.command()
async def ping1(ctx):
await ctx.send("pong!")
#client.event
async def on_ready():
await client.change_presence(status=discord.Status.online, activity=discord.Game("cranking 90s on shitters"))
print("bot is ready!")
#client.event
async def on_member_join(member):
print(f'{member} has joined :weary:.')
#client.event
async def on_member_remove(member):
print(f'{member} has left :weary:')
#client.command()
async def helb(ctx):
await ctx.send('#everyone look at this idiot')
#client.command()
async def ping(ctx):
await ctx.send(f'here you go: {round(client.latency * 1000)}ms')
#client.command()
async def commands(ctx):
await ctx.send('1. helb it will help you. 2. ping it will tell you the bots ping. ')
#client.command()
async def overlord(ctx):
await ctx.send("muah hah hah YOUR SERVER IS MINE")
keywords = ["mcguccy is an idiot", "kick mcguccy", "i want to nuke the server"]
#client.event
async def on_message(message):
for i in range(len(keywords)):
if keywords[i] in message.content:
for j in range(20):
await message.channel.send(f"#everyone someone has spammed :weary:")
There are a few things to look at here:
Your client variable is a Bot type, not a Client type.
client = commands.Bot(command_prefix='!')
This means you need to use #bot decorators instead of #client decorators:
#client.command()
async def helb(ctx):
...
# Becomes
#bot.command()
async def helb(ctx):
...
The .run() method is never called.
Because of this, the bot's event loop doesn't start. You need to initialize the Client event loop so the bot can listen for commands to pass:
if __name__=='__main__':
client.run(TOKEN)
That code needs to be the very last statement run in the file, as it's blocking.
The .run() command requires an API token.
You can acquire said token by creating a bot account if you don't have one already. If you do have one, you'll need to pass it as the first paramater to the .run() method.

Discord.py ctx.guild.edit works but not self.bot.guild.edit?

Like the title says,
I'm trying to do guild edits but on an events.
Here's part of my code:
#commands.guild_only()
async def on_ready(self):
server = self.bot.get_guild("serverid")
while True:
await self.bot.guild.edit(guild=server, name="foo")
await asyncio.sleep(1)
await self.bot.guild.edit(guild=server, name="bar")
await asyncio.sleep(1)
I've already tested it with a standalone command, so I know that ctx.guild.edit works but I'm not sure how to get it to work in an event.
You should call edit directly from the Guild object server
async def on_ready(self):
server = self.bot.get_guild(SERVER_ID)
while server is not None:
await server.edit(name="foo")
await asyncio.sleep(1)
await server.edit(name="bar")
await asyncio.sleep(1)
Also, make sure that you're passing the id of the guild as an int and not a string, and the guild_only decorator should only be used on commands.

Commands not being recognized by discord.py

I have a simple discord.py set up trying to use .ping, but in this current instance, the actual sending of ".ping" results in nothing being sent by the bot. Is there something I'm missing here?
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix = ".")
#bot.event
async def on_ready():
print("Everything's all ready to go~")
#bot.event
async def on_message(message):
author = message.author
content = message.content
print(content)
#bot.event
async def on_message_delete(message):
author = message.author
channel = message.channel
await bot.send_message(channel, message.content)
#bot.command()
async def ping():
await bot.say('Pong!')
bot.run('Token')
Ensure that you have await bot.process_commands(message) somewhere in your on_message event.
Why does on_message make my commands stop working?
Overriding the default provided on_message forbids any extra commands from running. To fix this, add a bot.process_commands(message) line at the end of your on_message. For example:
#bot.event
async def on_message(message):
# do some extra stuff here
await bot.process_commands(message)
https://discordpy.readthedocs.io/en/latest/faq.html#why-does-on-message-make-my-commands-stop-working

Categories