TwitchIO not recognizing the command used before - python

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

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.

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.

!help [command_name] discord.py

I’m creating a discord bot using python. I did a custom help command (don’t worry, for this part I’m ok), and I want to do a !help [command_name]. Let me explain. If we do !help, the bot will send the basic help command, but if I do !help [command_name], like !help ping, it will send informations a bout the ping command. I tried to do this
#bot.command()
async def help ping(ctx):
…
await ctx.send(embed=embed)
#bot.command()
async def help(ctx):
…
await ctx.send(embed=embed)
It didn’t worked, so I did this:
#bot.event
async def on_message(message):
if message.content.startswith(+help ping):
…
await message.channel.send(embed=embed)
#bot.command()
async def help(ctx):
…
await ctx.send(embed=embed)
There, the !help ping worked, but not the !help. And now, I’m there. Can you tell me a simple solution using #bot.command() or #bot.event?
You can also do Grouping on the commands.
Example :
#client.group(invoke_without_command = True) # for this main command (.help)
async def help(ctx):
await ctx.send("Help! Categories : Moderation, Utils, Fun")
#help.command() #For this command (.help Moderation)
async def Moderation(ctx):
await ctx.send("Moderation commands : kick, ban, mute, unban")
#help.command() #And for this command (.help Utils)
async def Uitls(ctx):
await ctx.send("Utils : ping, prefix")
#help.command() #And lastly this command (.help Fun)
async def Fun(ctx):
await ctx.send("Fun : 8ball, poll, headsortails")
Thank me later :D
...
from discord.ext.commands import Cog, Group, Command, HelpCommand
... # bot and bot commands
class MyCustomHelpCommand(HelpCommand):
async def send_bot_help(self, mapping): # Mapping[Optional[Cog], List[Command]]
... # write you'r help message here
self.get_destination().send(message)
async def send_cog_help(self, cog: Cog):
... # write you'r help message here
self.get_destination().send(message)
async def send_group_help(self, group: Group):
... # write you'r help message here
self.get_destination().send(message)
async def command_not_find(self):
... # write you'r help message here
self.get_destination().send(message)
bot.help_command = MyCustomHelpCommand()
docs: HelpCommand
also see: DefaultHelpCommand, MinimalHelpCommand
try it:
...
from discord.ext.commands import Command
... # bot and bot commands
# command example 1
#client.command(help='I am an example')
async def ex1(ctx):
await ctx.send('I am working')
# command example 2
#client.command()
async def ex2(ctx):
'''I am an example too'''
await ctx.send('I am working too')
#client.command(name='help')
async def my_help_command(ctx, command_name: str = 'help')
await ctx.send(client.get_command(command_name) or 'Command Not Find')
Output with '!' command_perfix:
me: !help ex1
bot: I am an example
me: !help ex2
bot: I am an example too
me: !help i_an_not_command
bot: Command Not Find
You can do this:
#bot.commands()
async def help(ctx, cmd=None):#if the user doesn't give any arguments for "cmd" then it will count it as None
if not cmd:#checks if the user gave arguments for "cmd"
await ctx.send("Help is here!")#the message the bot should send
elif cmd.lower()=="ping":#checks if the arguments given for "cmd" is ping and I set "cmd.lower()" so that the argument is not case sensitive
await ctx.send("Help for command `ping` is here!")
else:#if the arguments doesn't match any of the if statements it will show an error
await ctx.send(f"No command named `{cmd.lower()}`")#you can set anything for the error message
Hope you find it helpful
And sorry for answering this late

Bypass on_command_error(ctx) and call variable of other function

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)

How to get discord.py bot to DM a specific user

I have searched around a lot for this answer, and I haven't found it. I want to use a suggestion command, that whenever someone uses it to suggest an idea, it DMs me, and me only.
You'll have to use the send_message method. Prior to that, you have to find which User correspond to yourself.
#client.event
async def on_message(message):
# we do not want the bot to reply to itself
if message.author == client.user:
return
# can be cached...
me = await client.get_user_info('MY_SNOWFLAKE_ID')
await client.send_message(me, "Hello!")
#client.event
async def on_message(message):
if message.content.startswith("#whatever you want it to be")
await client.send_message(message.author, "#The message")
Replace the hashtagged things with the words that you want it to be. eg.: #whatever you want it to be could be "!help". #The message could be "The commands are...".
discord.py v1.0.0+
Since v1.0.0 it's no longer client.send_message to send a message, instead you use send() of abc.Messageable which implements the following:
discord.TextChannel
discord.DMChannel
discord.GroupChannel
discord.User
discord.Member
commands.Context
Example
With bot.command() (recommended):
from discord.ext import commands
bot = commands.Bot(command_prefix="!")
#bot.command()
async def suggest(ctx, *, text: str):
me = bot.get_user(YOUR_ID)
await me.send(text) # or whatever you want to send here
With on_message:
from discord.ext import commands
bot = commands.Bot()
#bot.event
async def on_message(message: discord.Message):
if message.content.startswith("!suggest"):
text = message.content.replace("!suggest", "")
me = bot.get_user(YOUR_ID)
await me.send(text) # or whatever you want to send here

Categories