Use pycord to make a music bot - python

My English is not good, I am still a newcomer, please forgive me if the question is not good.
I'm using PyCord 2.3.2 to make a discord music robot. Currently, I only do the join command. Although I can join the channel, it throws an error.
Ignoring exception in command join:
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 178, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\user\Desktop\BOT\Cogs\Music.py", line 52, in join
await channel.connect()
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\abc.py", line 1932, in connect
await voice.connect(timeout=timeout, reconnect=reconnect)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\voice_client.py", line 404, in connect
self.ws = await self.connect_websocket()
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\voice_client.py", line 375, in connect_websocket
await ws.poll_event()
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\gateway.py", line 944, in poll_event
await self.received_message(utils._from_json(msg.data))
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\gateway.py", line 861, in received_message
await self.initial_connection(data)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\gateway.py", line 898, in initial_connection
recv = await self.loop.sock_recv(state.socket, 70)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 696, in sock_recv
return await self._proactor.recv(sock, n)
RuntimeError: Task <Task pending name='pycord: on_message' coro=<Client._run_event() running at C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py:377>> got Future <_OverlappedFuture pending overlapped=<pending, 0x183de095fc0>> attached to a different loop
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\bot.py", line 347, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 950, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\ext\commands\core.py", line 187, in wrapped
raise CommandInvokeError(exc) from exc
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: RuntimeError: Task <Task pending name='pycord: on_message' coro=<Client._run_event() running at C:\Users\user\AppData\Local\Programs\Python\Python310\lib\site-packages\discord\client.py:377>> got Future <_OverlappedFuture pending overlapped=<pending, 0x183de095fc0>> attached to a different loop
I tried to find the problem according to the error, but there is no good solution, hope to find a solution here.
this is my program
Cogs:
import discord
from discord.ext import commands,tasks
import os
import youtube_dl
import asyncio
from definition.Classes import Cog_Extension
class Music(Cog_Extension):
#commands.command(name='join', help='Tells the bot to join the voice channel')
async def join(self,ctx):
if not ctx.message.author.voice:
await ctx.send("{} is not connected to a voice channel".format(ctx.message.author.name))
return
else:
channel = ctx.message.author.voice.channel
await channel.connect()
def setup(bot):
bot.add_cog(Music(bot))
Bot:
import discord
import asyncio
from discord.ext import commands
import os
import json
with open("config.json" , "r" ,encoding="utf8") as configFiles:
config = json.load(configFiles)
intents = discord.Intents.all()
bot = commands.Bot(command_prefix=config["command_prefix"], intents=intents)
#bot.event
async def on_ready():
os.system('clear')
print("-"*15)
print("🌐bot online")
print("-"*15)
print(bot.user.name)
print(bot.user.id)
print(bot.user)
print("-"*15)
Activity = discord.Activity(type=discord.ActivityType.watching,name="bot")
await bot.change_presence(activity=Activity)
await asyncio.sleep(3)
async def load():
for filename in os.listdir('./Cogs'):
if filename.endswith('.py'):
try:
bot.load_extension(f'Cogs.{filename[:-3]}')
print(f'✅ load {filename}')
except Exception as error:
print(f'❎ {filename} error {error}')
async def main():
await load()
await bot.start(config["Token"])
asyncio.run(main())

I think you could simplify your code a bit and that'll likely help:
def load():
# doesn't need to be async
for filename in os.listdir('./Cogs'):
if filename.endswith('.py'):
try:
bot.load_extension(f'Cogs.{filename[:-3]}')
print(f'✅ load {filename}')
except Exception as error:
print(f'❎ {filename} error {error}')
load()
bot.run(config["Token"])
Or, if you really want to use bot.start then the docs recommend doing it this way:
def load():
# still doesn't need to be async
for filename in os.listdir('./Cogs'):
if filename.endswith('.py'):
try:
bot.load_extension(f'Cogs.{filename[:-3]}')
print(f'✅ load {filename}')
except Exception as error:
print(f'❎ {filename} error {error}')
load()
# for python3.11
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
# loop = asyncio.get_event_loop()
try:
loop.run_until_complete(bot.start(config["Token"]))
except KeyboardInterrupt:
loop.run_until_complete(close())
# cancel all tasks lingering
finally:
loop.close()
I used the latter method, and copied your cog and my bot joined the VC I was in without any issues.

Related

How can I close a discord client connection without exception

Let's say I have a simple discord.Client code:
import os
import discord
from dotenv import load_dotenv
load_dotenv()
intents = discord.Intents.default()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.getenv('DISCORD_GUILD')
client = discord.Client(intents=intents)
#client.event
async def on_ready():
guild = None
for guild in client.guilds:
if guild.name == GUILD:
break
print(
f'{client.user} is connected to guild {guild.name} (id: {guild.id})'
)
client.run(TOKEN)
So, when I stop the code, I get this exception:
Traceback (most recent call last):
File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 116, in __del__
self.close()
File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 751, in call_soon
self._check_closed()
File "C:\Users\HP\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 515, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
Process finished with exit code 0
It does not affect the code and functionality in any way, but it is very annoying to see.
How would I disconnect/close connection properly then?
So, after a bit of searching, I found that the
#client.event
async def close():
print(f"{client.user} disconnected")
works just fine.

Hey Every Time I wanna run my bot it tells me this error

Hey Every Time I wanna run my bot it tells me this error but it runs anyway. I wanna know how can I fix it?
ERROR:
Unhandled exception in internal background task 'ch_pr'.Traceback (most recent call last): File "C:\Users\Pekah\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\ext\tasks\__init__.py", line 178, in _loop await self.coro(*args, **kwargs) File "c:\Users\Pekah\OneDrive\Documents\Projects\rare-bot\bot.py", line 32, in ch_pr await client.change_presence(activity=discord.Game(name=f'Rare Bot version: {version} 🔧')) File "C:\Users\Pekah\AppData\Local\Programs\Python\Python39-32\lib\site-packages\discord\client.py", line 1112, in change_presence await self.ws.change_presence(activity=activity, status=status_str)AttributeError: 'NoneType' object has no attribute 'change_presence'
CODE:
#tasks.loop(seconds=5)
async def ch_pr():
while True:
await client.change_presence(activity=discord.Game(name=f'Rare Bot version: {version} 🔧'))
await asyncio.sleep(5)
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.listening ,name='-help 🌌'))
await asyncio.sleep(5)
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.listening ,name=f'{len(client.guilds)} servers 👾'))
await asyncio.sleep(5)
await client.change_presence(activity=discord.Game(name='discord.py 📁'))
await asyncio.sleep(5)
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.listening ,name=f'{len(client.users)} users 👥'))
await asyncio.sleep(5)
ch_pr.start()
You can use try/except to handle exceptions and carry on as normal. i.e.
while True:
try:
a_function_that_might_error()
except AttributeError:
pass #do nothing
However, this will catch all AttributeErrors. You'd be better off adjusting your code to ensure that the error doesn't happen, or by getting it to throw a more specific custom error that you can catch.

Callback for ping command is missing "ctx" parameterDiscord.py cog's command error

I am trying to make discord bot with discord.py library. So, I made two files - main.py and cog named - auto-reply.py. When I start main.py file everything is still ok, but when I try to use command from cog auto-reply.py it says
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\owner\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 690, in _parse_arguments
next(iterator)
StopIteration
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\owner\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\owner\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 979, in on_message
await self.process_commands(message)
File "C:\Users\owner\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 976, in process_commands
await self.invoke(ctx)
File "C:\Users\owner\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\owner\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 855, in invoke
await self.prepare(ctx)
File "C:\Users\owner\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 789, in prepare
await self._parse_arguments(ctx)
File "C:\Users\owner\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\ext\commands\core.py", line 693, in _parse_arguments
raise discord.ClientException(fmt.format(self))
discord.errors.ClientException: Callback for ping command is missing "ctx" parameter.
My main.py file:
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix=">")
#bot.event
async def on_ready():
print(f'{bot.user} has connected to Discord!')
#bot.command(name="hi")
async def hello_world(ctx: commands.Context):
await ctx.send("Hey!")
bot.load_extension("cogs.fun.auto-reply")
bot.run("OTA2MTY5Nzk2MDI5MjAyNTAz.YYUuYw.Ox1q8_397DU9FWYHtuS101f_wns")
And auto-reply.py file:
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix=">")
class autoreply(commands.Cog):
def __init__(self, bot):
self.bot = bot
#bot.command(name="ping")
async def yo(ctx: commands.Context):
await ctx.send("pong")
def setup(bot):
bot.add_cog(autoreply(bot))
I use python 3.9 and discord.py 1.7.3. I will be happy if you guys can help me :D

How to fix "discord.ext.commands.errors.MissingRequiredArgument: ctx is a required argument that is missing." in discord.py

I'm trying do a simple bot with subclass to handler the commands but i got this error
Here Are the TraceBack:
Ignoring exception in command teste:
Traceback (most recent call last):
File "/home/mrtrue/.local/lib/python3.8/site-packages/discord/ext/commands/bot.py", line 863, in invoke
await ctx.command.invoke(ctx)
File "/home/mrtrue/.local/lib/python3.8/site-packages/discord/ext/commands/core.py", line 721, in invoke
await self.prepare(ctx)
File "/home/mrtrue/.local/lib/python3.8/site-packages/discord/ext/commands/core.py", line 685, in prepare
await self._parse_arguments(ctx)
File "/home/mrtrue/.local/lib/python3.8/site-packages/discord/ext/commands/core.py", line 599, in _parse_arguments
transformed = await self.transform(ctx, param)
File "/home/mrtrue/.local/lib/python3.8/site-packages/discord/ext/commands/core.py", line 445, in transform
raise MissingRequiredArgument(param)
discord.ext.commands.errors.MissingRequiredArgument: ctx is a required argument that is missing.
And here are the code:
import discord
from discord.ext import commands
import inspect
class BotLibertarin(commands.Bot):
client = discord.Client()
#client.event
async def on_message(self,message):
print(f"message from {message.author} what he said {message.content}")
await self.process_commands(message)
class CommandsHandler(BotLibertarin):
def __init__(self):
super().__init__(command_prefix=".")
members = inspect.getmembers(self)
for name, member in members:
if isinstance(member,commands.Command):
if member.parent is None:
self.add_command(member)
#commands.command()
async def teste(self,ctx):
await ctx.channel.send("teste")
I really suggest that you spend time reading the docs.
I'd also remind you that it's against ToS to send messages without a specific command being issued (such as !commandname) [Even though no one follows ToS apparently].
Either way. Try this:
import discord
from discord.ext import commands
client = commands.Bot(command.prefix='!')
#client.event
async def on_message(message):
print(f"message from {message.author} what he said {message.content}")
await message.channel.send(message.content)
#client.command()
async def teste(ctx):
await ctx.channel.send("teste")

Join voice channel (discord.py)

When I try to let my bot join my voice channel, I get this error:
await client.join_voice_channel(voice_channel) (line that generates the error)
Traceback (most recent call last):
File "/usr/local/lib/python3.5/site-packages/discord/ext/commands/core.py", line 50, in wrapped
ret = yield from coro(*args, **kwargs)
File "bot.py", line 215, in sfx
vc = await client.join_voice_channel(voice_channel)
File "/usr/local/lib/python3.5/site-packages/discord/client.py", line 3176, in join_voice_channel
session_id_future = self.ws.wait_for('VOICE_STATE_UPDATE', session_id_found)
AttributeError: 'NoneType' object has no attribute 'wait_for'
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "/usr/local/lib/python3.5/site-packages/discord/ext/commands/bot.py", line 848, in process_commands
yield from command.invoke(ctx)
File "/usr/local/lib/python3.5/site-packages/discord/ext/commands/core.py", line 369, in invoke
yield from injected(*ctx.args, **ctx.kwargs)
File "/usr/local/lib/python3.5/site-packages/discord/ext/commands/core.py", line 54, in wrapped
raise CommandInvokeError(e) from e
discord.ext.commands.errors.CommandInvokeError: Command raised an exception: AttributeError: 'NoneType' object has no attribute 'wait_for'
I'm getting this error with channel name and channel ID
Function:
description = "Bot"
bot_prefix = "!"
client = discord.Client()
bot = commands.Bot(description=description, command_prefix=bot_prefix)
#bot.command(pass_context=True)
async def join(ctx):
author = ctx.message.author
voice_channel = author.voice_channel
vc = await client.join_voice_channel(voice_channel)
This is the code i use to make it work.
#Bot.py
import discord
from discord.ext import commands
from discord.ext.commands import Bot
from discord.voice_client import VoiceClient
import asyncio
bot = commands.Bot(command_prefix="|")
async def on_ready():
print ("Ready")
#bot.command(pass_context=True)
async def join(ctx):
author = ctx.message.author
channel = author.voice_channel
await bot.join_voice_channel(channel)
bot.run("token")
Get rid of the
from discord.voice_client import VoiceClient
line and it shoudl be ok.
Try this
await bot.join_voice_channel(channel)

Categories

Resources