Cannot close a running event loop discord.py - python

I've migrating my discord bot to use MySQL instead of storing data in json files. The only problem I got now is when I try to load the music extension of the bot...
Code:
import discord
import lavalink
from discord import Guild
from discord import User
from discord.ext import commands
# from bot import get_musicchannel
# from bot import get_prefix
from bot import mycursor
def get_musicchannel(guild: Guild):
# with open("cogs/music.json") as f:
# channels = json.load(f)
# channel: TextChannel = discord.utils.get(guild.text_channels, id=channels[str(guild.id)])
# return channel.id
sqlcommand = "SELECT channelid FROM musicchannels WHERE guildid = %s"
vals = (guild.id,)
mycursor.execute(sqlcommand, vals)
result = mycursor.fetchall()
strchannelid = str(result[0]).replace("(", "").replace(")", "").replace(",", "")
channelid = int(strchannelid)
return channelid
class Music(commands.Cog):
def __init__(self, bot):
self.bot = bot
self.bot.music = lavalink.Client(self.bot.user.id)
self.bot.music.add_node("IP", 2333, 'PASS', 'eu', 'music-node')
self.bot.add_listener(self.bot.music.voice_update_handler, 'on_socket_response')
self.bot.music.add_event_hook(self.track_hook)
#commands.command(name="music")
async def music(self, ctx, opt, *, arg=None):
if ctx.message.channel.id != get_musicchannel(ctx.guild):
# channel = get_musicchannel(ctx.guild)
actual_channel = discord.utils.get(ctx.guild.text_channels, id=get_musicchannel(ctx.guild))
return await ctx.send(f"Music commands can only be used in the music channel ({actual_channel.mention})")
if opt == "join":
member = discord.utils.find(lambda m: m.id == ctx.author.id, ctx.guild.members)
if member is not None and member.voice is not None:
vc = member.voice.channel
player = self.bot.music.player_manager.create(ctx.guild.id, endpoint=str(ctx.guild.region))
if not player.is_connected:
player.store('channel', ctx.guild.id)
await self.connect_to(ctx.guild.id, str(vc.id))
# Unimportant code
async def track_hook(self, event):
if isinstance(event, lavalink.events.QueueEndEvent):
guild_id = int(event.player.guild_id)
await self.connect_to(guild_id, None)
async def connect_to(self, guild_id: int, channel_id: int):
ws = self.bot._connection._get_websocket(guild_id)
await ws.voice_state(str(guild_id), channel_id)
async def disconnect_from(self, guild_id: int):
ws = self.bot._connection.voice_clients
print(ws)
def setup(bot):
bot.add_cog(Music(bot))
When I try to run the bot it gives me this error:
Ignoring exception in on_ready
Traceback (most recent call last):
File "C:\Users\xlysa\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 668, in run
loop.run_forever()
File "C:\Users\xlysa\AppData\Local\Programs\Python\Python38-32\lib\asyncio\windows_events.py", line 314, in run_forever
assert self._self_reading_future is None
AssertionError
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\xlysa\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 93, in _cleanup_loop
_cancel_tasks(loop)
File "C:\Users\xlysa\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 78, in _cancel_tasks
loop.run_until_complete(asyncio.gather(*tasks, return_exceptions=True))
File "C:\Users\xlysa\AppData\Local\Programs\Python\Python38-32\lib\asyncio\base_events.py", line 592, in run_until_complete
self._check_running()
File "C:\Users\xlysa\AppData\Local\Programs\Python\Python38-32\lib\asyncio\base_events.py", line 552, in _check_running
raise RuntimeError('This event loop is already running')
RuntimeError: This event loop is already running
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\xlysa\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 607, in _load_from_module_spec
spec.loader.exec_module(lib)
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "D:\Ficheiros\Pastas\Tudo\Coding\Python\Projects\Server-Utils\cogs\music.py", line 11, in <module>
from bot import mycursor
File "D:\Ficheiros\Pastas\Tudo\Coding\Python\Projects\Server-Utils\bot.py", line 1383, in <module>
bot.run(TOKEN)
File "C:\Users\xlysa\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 674, in run
_cleanup_loop(loop)
File "C:\Users\xlysa\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 98, in _cleanup_loop
loop.close()
File "C:\Users\xlysa\AppData\Local\Programs\Python\Python38-32\lib\asyncio\proactor_events.py", line 674, in close
raise RuntimeError("Cannot close a running event loop")
RuntimeError: Cannot close a running event loop
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\xlysa\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\client.py", line 312, in _run_event
await coro(*args, **kwargs)
File "D:/Ficheiros/Pastas/Tudo/Coding/Python/Projects/Server-Utils/bot.py", line 421, in on_ready
bot.load_extension('cogs.music')
File "C:\Users\xlysa\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 664, in load_extension
self._load_from_module_spec(spec, name)
File "C:\Users\xlysa\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 610, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.music' raised an error: RuntimeError: Cannot close a running event loop
Process finished with exit code 0
The on_ready event just has bot.load_extension('cogs.music') that's where the error comes from
I don't know what can I do to make this run... Help is appreciated.

Related

Event loop is closed.Called after closing the discord bot

After completion (shutdown) the bot gives an error. Error:
Traceback (most recent call last):
File "E:\Python v 3.10\lib\asyncio\proactor_events.py", line 116, in __del__
self.close()
File "E:\Python v 3.10\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "E:\Python v 3.10\lib\asyncio\base_events.py", line 745, in call_soon
self._check_closed()
File "E:\Python v 3.10\lib\asyncio\base_events.py", line 510, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x000001BEC7630310>
Traceback (most recent call last):
File "E:\Python v 3.10\lib\asyncio\proactor_events.py", line 116, in __del__
File "E:\Python v 3.10\lib\asyncio\proactor_events.py", line 108, in close
File "E:\Python v 3.10\lib\asyncio\base_events.py", line 745, in call_soon
File "E:\Python v 3.10\lib\asyncio\base_events.py", line 510, in _check_closed
RuntimeError: Event loop is closed
My code:
TOKEN = 'token'
class MyClient(discord.Client):
async def on_ready(self):
print('Logged on as', self.user)
async def on_message(self, message):
# don't respond to ourselves
if message.author == self.user:
return
if message.content == 'ping':
await message.channel.send('pong')
client = MyClient()
client.run(TOKEN)
The bot issues such an error after the program is completed. How to fix it?
Solutions like:
change token
token is invalid
These solutions didn't help me.
The only thing I have improved all the libraries that were. Discord itself, aiohttp and asyncio. But they did not lead to a result. What can such a problem be related to? Bot code, example:
This is an aiohttp bug on Windows.
There doesn't seem to be a solution at the moment.
https://github.com/aio-libs/aiohttp/issues/4324

Music bot returning errors at core.py and bot.py

The code for the music bot I'm trying to write in python keeps returning an error with the following code:
#bot.command(name='play_song', help='To play song')
async def play(ctx,url):
#if not ctx.message.author.name=="Rohan Krishna" :
# await ctx.send('NOT AUTHORISED!')
# return
if 1==1:#try :
server = ctx.message.guild
voice_channel = server.voice_client
print("try 1 was a success")
async with ctx.typing():
filename = await YTDLSource.from_url(url, loop=bot.loop)
#voice_channel.play(discord.FFmpegPCMAudio(executable="ffmpeg.exe", source=filename)) #ISSUE HERE
print("try 2 was a success")
voice = get(ctx.bot.voice_clients, guild=ctx.guild)
#voice.play(discord.FFmpegPCMAudio('test.mp3'), after=your_check)
#voice.source = discord.PCMVolumeTransformer(voice.source)
#voice.source.volume = 0.5
await ctx.send('**Now playing:** {}'.format(filename))
if 1==0:#except:
await ctx.send("The bot is not connected to a voice channel.")
print("try 3 was unfortunately a success")
It normally has a try/except function but I replaced it with if true and false statements to force it to run instead of breaking to determine the exact line of it breaking. The issue supposedly lies in
voice_channel.play(discord.FFmpegPCMAudio(executable="ffmpeg.exe", source=filename)) #ISSUE HERE
The error I get returned is:
Traceback (most recent call last):
File "C:\Users\heyin\anaconda3\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "app2.py", line 75, in play
voice.play(discord.FFmpegPCMAudio('test.mp3'), after=your_check)
File "C:\Users\heyin\anaconda3\lib\site-packages\discord\player.py", line 225, in __init__
super().__init__(source, executable=executable, args=args, **subprocess_kwargs)
File "C:\Users\heyin\anaconda3\lib\site-packages\discord\player.py", line 138, in __init__
self._process = self._spawn_process(args, **kwargs)
File "C:\Users\heyin\anaconda3\lib\site-packages\discord\player.py", line 147, in _spawn_process
raise ClientException(executable + ' was not found.') from None
discord.errors.ClientException: ffmpeg was not found.
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\heyin\anaconda3\lib\site-packages\discord\ext\commands\bot.py", line 939, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\heyin\anaconda3\lib\site-packages\discord\ext\commands\core.py", line 863, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\heyin\anaconda3\lib\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: ClientException: ffmpeg was not found.
I added the print statements to determine which lines were working so those can obviously be ignored. It seems to be working fine except for this, other commands in the bot are working appropriately.

futures timeout error in the telegram bot, concurrent.futures._base.TimeoutError

I have created a telegram bot. where I am asking the users to send the location.
import aioschedule as schedule
import asyncio
from asyncio import futures
#bot.on(events.CallbackQuery(pattern=r'sendloc'))
async def sendlocation(event):
sender = await event.get_input_sender()
my_user = await bot.get_entity(sender.user_id)
userId = my_user.id
async with bot.conversation(userId) as conv:
await conv.send_message('receiving', buttons=[Button.request_location(text='send Location', resize=10)])
try:
response = await conv.get_response()
except futures.TimeoutError as e:
await conv.cancel_all()
return
conv.send_message('location accepted')
async def methodToSendLocation():
users = pd.read_csv('telegramId.csv')
for user in users['Telegram ID']:
try:
await bot.send_message(user, 'send location', buttons=Button.inline('sendloc'))
except ValueError as e:
print('Error occurred for user: {telId}'.format(telId=user))
def main():
'''start the bot'''
bot.start()
schedule.every().day.at("11:00").do(methodToSendLocation)
loop = asyncio.get_event_loop()
while True:
loop.run_until_complete(schedule.run_pending())
bot.run_until_disconnected()
if __name__ == '__main__':
main()
what does my program do?
It will run every day at 11:00 AM.
It will fetch the telegram Id from the CSV file and send a message to the users to send the location and we process the location.
My Query:
Sometimes there occurs a timeout error in sendlocation method of my program and recently I observed that for some users timeout error occurred within a minute after the user clicks the send Location button.
I am not able to understand why the error occurred in a very short interval.
And sometimes there has been a delay to send the location to the bot after the user clicks the send Location button.
stack trace:
Traceback (most recent call last):
File "app.py", line 118, in sendlocation
response = await conv.get_response()
File "C:\Users\Swarnim\AppData\Local\Programs\Python\Python37-32\lib\asyncio\tasks.py", line 449, in wait_for
raise futures.TimeoutError()
concurrent.futures._base.TimeoutError
Stack (most recent call last):
File "app.py", line 450, in <module>
main()
File "app.py", line 444, in main
loop.run_until_complete(schedule.run_pending())
File "/usr/lib/python3.6/asyncio/base_events.py", line 471, in run_until_complete
self.run_forever()
File "/usr/lib/python3.6/asyncio/base_events.py", line 438, in run_forever
self._run_once()
File "/usr/lib/python3.6/asyncio/base_events.py", line 1451, in _run_once
handle._run()
File "/usr/lib/python3.6/asyncio/events.py", line 145, in _run
self._callback(*self._args)
File "/home/epluser/.venv/automation/lib/python3.6/site-packages/telethon/client/updates.py", line 443, in _dispatch_update
await callback(event)
File "app.py", line 121, in sendlocation

I'm about to give up on my first project with python which is making a discord bot, this will be my last question?

I keep getting errors with this project and this is probably the last one I'm gonna try to fix
here's the code that has the problem:
#classmethod
async def from_url(cls, url, *, loop=None, stream=False):
loop = loop or asyncio.get_event_loop()
data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=not stream))
if 'entries' in data:
# take first item from a playlist
data = data['entries'][0]
filename = data['url'] if stream else ytdl.prepare_filename(data)
return cls(discord.FFmpegPCMAudio(filename, **ffmpeg_options), data=data)
and this is the error:
Ignoring exception in command play:
Traceback (most recent call last):
File "C:\Users\moham\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "C:\Users\moham\Desktop\musicbot.py", line 104, in play
player = await YTDLSource.from_url(queue, loop=client.loop)
File "C:\Users\moham\Desktop\musicbot.py", line 40, in from_url
data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=not stream))
File "C:\Users\moham\AppData\Local\Programs\Python\Python38-32\lib\concurrent\futures\thread.py", line 57, in run
result = self.fn(*self.args, **self.kwargs)
File "C:\Users\moham\Desktop\musicbot.py", line 40, in <lambda>
data = await loop.run_in_executor(None, lambda: ytdl.extract_info(url, download=not stream))
File "C:\Users\moham\AppData\Local\Programs\Python\Python38-32\lib\site-packages\youtube_dl\YoutubeDL.py", line 788, in extract_info
if not ie.suitable(url):
File "C:\Users\moham\AppData\Local\Programs\Python\Python38-32\lib\site-packages\youtube_dl\extractor\common.py", line 413, in suitable
return cls._VALID_URL_RE.match(url) is not None
TypeError: expected string or bytes-like object
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\moham\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\bot.py", line 903, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\moham\AppData\Local\Programs\Python\Python38-32\lib\site-packages\discord\ext\commands\core.py", line 859, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\moham\AppData\Local\Programs\Python\Python38-32\lib\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: TypeError: expected string or bytes-like object
I am still new to all of this so please assume that I don't know a lot about coding, I was just following a tutorial and apparently I'm not even good at that lol.

Code "crashing" in await ClientResponse.text()

I'm trying to create an api, and when i try to convert the aiohttp.ClientResponse to text, my code never finishes (never go to the next line) and it raises TimeoutError, I tried to do this in terminal (with the same site), and it works, can someone help me?
Here's my current code:
async with aiohttp.ClientSession() as session:
# _base="https://frankerfacez.com"
# query="monka"
# sort="count-desc"
r = await session.get(f'{_base}/emoticons/wall?q={query}&sort={sort}')
txt = await r.text()
And it raises this:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\Kaigo\AppData\Local\Programs\Python\Python38\lib\asyncio\base_events.py", line 612, in run_until_complete
return future.result()
File "C:\Users\Kaigo\Desktop\FFZ Api\ffz\__init__.py", line 112, in search
txt = await r.text()
File "C:\Users\Kaigo\AppData\Local\Programs\Python\Python38\lib\site-packages\aiohttp\client_reqrep.py", line 1009, in text
await self.read()
File "C:\Users\Kaigo\AppData\Local\Programs\Python\Python38\lib\site-packages\aiohttp\client_reqrep.py", line 973, in read
self._body = await self.content.read()
File "C:\Users\Kaigo\AppData\Local\Programs\Python\Python38\lib\site-packages\aiohttp\streams.py", line 358, in read
block = await self.readany()
File "C:\Users\Kaigo\AppData\Local\Programs\Python\Python38\lib\site-packages\aiohttp\streams.py", line 380, in readany
await self._wait('readany')
File "C:\Users\Kaigo\AppData\Local\Programs\Python\Python38\lib\site-packages\aiohttp\streams.py", line 296, in _wait
await waiter
File "C:\Users\Kaigo\AppData\Local\Programs\Python\Python38\lib\site-packages\aiohttp\helpers.py", line 596, in __exit__
raise asyncio.TimeoutError from None
asyncio.exceptions.TimeoutError
you're trying to read from the request after clossing the session. Move the await r.text() to inside the async with block:
async with aiohttp.ClientSession() as session:
url = f'{_base}/emoticons/wall?q={query}&sort={sort}'
async with session.get(url) as r:
txt = await r.text()

Categories