I'm trying to make a music cog for my bot. I'm currently making commands for the bot to join and leave a voice channel. But everytime i try to launch both of these commands, the same error occurs.
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\Daniel\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 663, in _parse_arguments
next(iterator)
StopIteration
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Daniel\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\client.py", line 312, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Daniel\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 930, in on_message
await self.process_commands(message)
File "C:\Users\Daniel\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 927, in process_commands
await self.invoke(ctx)
File "C:\Users\Daniel\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 892, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Daniel\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 790, in invoke
await self.prepare(ctx)
File "C:\Users\Daniel\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 751, in prepare
await self._parse_arguments(ctx)
File "C:\Users\Daniel\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 666, in _parse_arguments
raise discord.ClientException(fmt.format(self))
discord.errors.ClientException: Callback for join/leave command is missing "ctx" parameter.
Here's the code i have:
import discord
from discord.ext import commands
import youtube_dl
class Music(commands.Cog):
def __init__(self, client):
self.client = client
#commands.command()
async def join(ctx):
channel = ctx.message.author.voice.channel
await channel.connect()
#commands.command()
async def leave(ctx):
await ctx.voice_client.diconnect()
def setup(client):
client.add_cog(Music(client))
Anyone know how i can fix this ?
You need to put self in your function async def join as well as your leave function:
#commands.command()
async def join(self, ctx):
channel = ctx.message.author.voice.channel
await channel.connect()
You're using a cog so you have a class with self that must be passed to classes not decorated with #staticmethod or #classmethod. With discord.py I recommend you do not do either of those for command/event functions you have above.
See: https://discordpy.readthedocs.io/en/latest/ext/commands/cogs.html
For cogs in discord.py
Related
I have an old bot that I'm trying to transfer to discord.py v2. Asyncpg isn't working and I'm not sure why. I've tried putting the loop and pool in the on_ready and setup_hook but that didn't work either.
import discord
from discord import app_commands
import aiohttp
import asyncio
import requests
from discord.ext import commands
import os
import asyncpg
# Pydest
# Define Client
class Aclient(commands.Bot):
def __init__(self):
super().__init__(command_prefix='.', intents=discord.Intents.default())
self.synced = False
async def setup_hook(self):
cog = await self.load_extension('cogs.weather')
print(f"Loaded All Cogs")
if not self.synced:
await self.tree.sync()
self.synced = True
async def on_ready(self):
await self.wait_until_ready()
if not self.synced:
await self.tree.sync()
self.synced = True
await client.change_presence(status=discord.Status.dnd)
print(f'We have logged in as {self.user}')
client=Aclient()
# test command
#client.tree.command(name="test", description="testing")
async def test(interaction: discord.Interaction, name: str):
async with pool.acquire() as connection:
async with connection.transaction():
check = await connection.fetchrow('select * from weather')
print(check)
await connection.close()
loop = asyncio.get_event_loop()
pool = loop.run_until_complete(asyncpg.create_pool(**credentials))
I'm getting this error:
Traceback (most recent call last):
File "/Users/prathik/Documents/GitHub/red/YELLOW/bot.py", line 61, in test
async with connection.transaction():
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/asyncpg/transaction.py", line 62, in __aenter__
await self.start()
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/asyncpg/transaction.py", line 138, in start
await self._connection.execute(query)
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/asyncpg/connection.py", line 317, in execute
return await self._protocol.query(query, timeout)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "asyncpg/protocol/protocol.pyx", line 338, in query
RuntimeError: Task <Task pending name='CommandTree-invoker' coro=<CommandTree._from_interaction.<locals>.wrapper() running at /Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/app_commands/tree.py:1089>> got Future <Future pending cb=[Protocol._on_waiter_completed()]> attached to a different loop
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/app_commands/commands.py", line 851, in _do_call
return await self._callback(interaction, **params) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Users/prathik/Documents/GitHub/red/YELLOW/bot.py", line 60, in test
async with pool.acquire() as connection:
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/asyncpg/pool.py", line 220, in release
raise ex
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/asyncpg/pool.py", line 210, in release
await self._con.reset(timeout=budget)
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/asyncpg/connection.py", line 1366, in reset
await self.execute(reset_query, timeout=timeout)
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/asyncpg/connection.py", line 317, in execute
return await self._protocol.query(query, timeout)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "asyncpg/protocol/protocol.pyx", line 323, in query
File "asyncpg/protocol/protocol.pyx", line 707, in asyncpg.protocol.protocol.BaseProtocol._check_state
asyncpg.exceptions._base.InterfaceError: cannot perform operation: another operation is in progress
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/app_commands/tree.py", line 1240, in _call
await command._invoke_with_namespace(interaction, namespace)
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/app_commands/commands.py", line 876, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/discord/app_commands/commands.py", line 869, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'test' raised an exception: InterfaceError: cannot perform operation: another operation is in progress
Does anyone know why this is happening?
import discord
from discord.ext import commands
bot = discord.ext.commands.Bot(command_prefix = ";");
import random
from asyncio import TimeoutError
import subprocess
import sys
from discord_components import *
class GameCommands(commands.Cog):
def __init__(self, bot):
self.bot=bot
#commands.Cog.listener()
async def on_ready(self):
DiscordComponents(bot)
print('ready')
#commands.command()
async def rps(self,ctx):
choices=['rock','paper','scissors']
bot_choise=random.choice(choices)
player_choise=""
yet= discord.Embed(title=f"{ctx.author.display_name}'s Rock Paper Scissors Game", description="Click On A Button", color=discord.Color.from_rgb(0, 208, 255))
won= discord.Embed(title=f"You Won! Le Hurray!", description=f"You chose {player_choise} and the Bot chose {bot_choise}", color=discord.Color.from_rgb(255, 213, 0))
lost= discord.Embed(title=f"You Lost! Sadge :(", description=f"You chose {player_choise} and the Bot chose {bot_choise}", color=discord.Color.from_rgb(102, 61, 69))
tie= discord.Embed(title=f"Hmm, A tie!", description=f"You and the bot both chose {bot_choise}", color=discord.Color.from_rgb(137, 49, 181))
out= discord.Embed(title=f"Timeout ", description=f"You didn't choose any option in time, Bruh!", color=discord.Color.from_rgb(43, 194, 146))
m = await ctx.send(embed=yet,components=[[Button(style=1 ,label="Rock"),Button(style=3 ,label="Paper"),Button(style=4 ,label="Scissors")]])
def check(res):
return ctx.author==res.user and res.channel==ctx.channel
try:
res= await self.bot.wait_for("button_click", check=check, timeout=15)
player_choise= res.component.label
if player_choise==bot_choise:
await m.edit(embed=tie, components=[])
if player_choise=="Paper" and bot_choise=="Rock":
await m.edit(embed=won, components=[])
if player_choise=="Scissors" and bot_choise=="Paper":
await m.edit(embed=won, components=[])
if player_choise=="Rock" and bot_choise=="Scissors":
await m.edit(embed=won, components=[])
if player_choise=="Rock" and bot_choise=="Paper":
await m.edit(embed=lost, components=[])
if player_choise=="Paper" and bot_choise=="Scissor":
await m.edit(embed=lost, components=[])
if player_choise=="Scissor" and bot_choise=="Rock":
await m.edit(embed=lost, components=[])
except TimeoutError:
await m.edit(embed=out, components=[])
def setup(bot):
bot.add_cog(GameCommands(bot))
I have discord-components installed, whenever i run the command i get this error:
Ignoring exception in command rps:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "/home/runner/TheDuck/commands/games.py", line 37, in rps
m = await ctx.send(embed=yet,components=[[Button(style=1 ,label="Rock"),Button(style=3 ,label="Paper"),Button(style=4 ,label="Scissors")]])
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord_components/client.py", line 46, in send_component_msg_prop
return await self.send_component_msg(ctxorchannel.channel, *args, **kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord_components/client.py", line 177, in send_component_msg
data = await self.bot.http.request(
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/http.py", line 192, in request
async with self.__session.request(method, url, **kwargs) as r:
AttributeError: 'NoneType' object has no attribute 'request'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/ext/commands/core.py", line 94, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'request'
I don't know what is causing this error. I tried finding about it online but couldn't.
I would Like to know what possible mistake i might be making or is it a bug.
I saw almost the same code being run on the main file without any problems. Is it a problem with cogs or my code is wrong?
While I am unsure if that is a bug or not, I think it would be better to use Discord.py 2.0 (Currently in Alpha) for buttons instead of third party libs. Keep in mind it might be unstable so is your choice.
I am making my bot for discord, I want to do this, when a user clicks on a certain voice channel, a new voice channel is created for him, which is deleted upon exit. Here is the code:
import discord
from discord.ext import commands
from discord.utils import get
import asyncio
TOKEN = 'xxxx'
bot = commands.Bot(command_prefix='!')
#bot.event
async def on_voice_state_update(member, before, after):
if after.channel != None:
if after.channel.id == 700246237244555338:
for guild in bot.guilds:
maincategory = discord.utils.get(
guild.categories, id=700246237244555336)
channel2 = guild.create_voice_channel(name=f'канал {member.display_name}', category=maincategory)
await channel2.set_permissions(member, connect=True, mute_members=True, manage_channels=True)
await member.move_to(channel2)
def check(x, y, z):
return len(channel2.members) == 0
await bot.wait_for('voice_state_update', check=check)
await channel2.delete()
# RUN
bot.run(TOKEN)
But i have error...
Ignoring exception in on_voice_state_update
Traceback (most recent call last):
File "C:\Users\asus\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\discord\client.py", line 333, in _run_event
await coro(*args, **kwargs)
File "jett.py", line 190, in on_voice_state_update
await member.move_to(channel2)
File "C:\Users\asus\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\discord\member.py", line 626, in move_to
await self.edit(voice_channel=channel, reason=reason)
File "C:\Users\asus\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\discord\member.py", line 592, in edit
payload['channel_id'] = vc and vc.id
AttributeError: 'coroutine' object has no attribute 'id'
C:\Users\asus\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\discord\client.py:340: RuntimeWarning: coroutine 'Guild.create_voice_channel' was never awaited
pass
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Can you help me with this problem or just send me working code for temporary voices
RuntimeWarning: Enable tracemalloc to get the object allocation traceback usually means that you forgot to add an await keyword to an async function. The async function in question is likely create_voice_channel, as the documentation says it is an async function.
To fix this, you'll want to add the await keyword before the function call, similar to this:
channel2 = await guild.create_voice_channel(name=f'канал {member.display_name}', category=maincategory)
My code
#bot.event
async def on_message(message):
emoji = '🎨'
message = message.id
await bot.add_reaction(message, emoji)
Error in console
Ignoring exception in on_message
Traceback (most recent call last):
File "/home/runner/.local/share/virtualenvs/python3/lib/python3.7/site-packages/discord/client.py", line 270, in _run_event
await coro(*args, **kwargs)
File "main.py", line 31, in on_message
AttributeError: 'Bot' object has no attribute 'add_reaction'
How to fix this error?
As the python interpreter helpfully points out, your Bot object doesn't have the function add_reaction(). Instead, it's available to the Message object:
#bot.event
async def on_message(message):
emoji = '🎨'
await message.add_reaction(emoji)
You can look at their FAQ for more help: "How do I add a reaction to a message?"
I'm making a discord bot in discord.py that kicks any member that sends a certain string, but I get the error "discord.errors.ClientException: Command kick is already registered."
bot = commands.Bot(command_prefix=',')
#client.event
async def on_message(message):
if message.author == client.user:
return
if "kick me"in message.content:
#bot.command(name="kick", pass_context=True)
#has_permissions(kick_members=True)
async def _kick(ctx, member: Member):
await bot.kick(member)
Instead of kicking the member, I get this lovely traceback:
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\Jason\AppData\Local\Programs\Python\Python35\lib\site-packages\discord\client.py", line 307, in _run_event
yield from getattr(self, event)(*args, **kwargs)
File "C:\Users\Jason\AppData\Local\Programs\Python\Python35\PrawnBot.py", line 66, in on_message
async def _kick(ctx, member: Member):
File "C:\Users\Jason\AppData\Local\Programs\Python\Python35\lib\site-packages\discord\ext\commands\core.py", line 574, in decorator
self.add_command(result)
File "C:\Users\Jason\AppData\Local\Programs\Python\Python35\lib\site-packages\discord\ext\commands\core.py", line 487, in add_command
raise discord.ClientException('Command {0.name} is already registered.'.format(command))
discord.errors.ClientException: Command kick is already registered.
Whenever the message !kick me is sent, you're re-registering the command. The command should be at the top level of your script or cog, not recreated every time the event is called.
bot = commands.Bot(command_prefix=',')
#bot.event
async def on_message(message)
...
await bot.process_commands(mesage)
#bot.command(name="kick", pass_context=True)
#has_permissions(kick_members=True)
async def _kick(ctx, member: Member):
await bot.kick(member)