RuntimeError: Cannot enter into task while anothe task is being executed - python

So i'm on Spyder trying to connect my discord bot and i'm running this code :
import discord
import nest_asyncio
nest_asyncio.apply()
client = discord.Client()
#client.event
async def on_ready():
print('The bot is ready')
#client.event
async def on_message(message):
if message.content.lower()=='ping':
await message.channel.send('pong')
client.run(token)
And i'm facing this error :
Exception in callback <TaskStepMethWrapper object at 0x000002A55BF8DF40>() handle: <Handle <TaskStepMethWrapper object at 0x000002A55BF8DF40>()>
Traceback (most recent call last):
File "C:\Users\33767\anaconda3\lib\asyncio\events.py", line 80, in _run
self._context.run(self._callback, *self._args)
RuntimeError: Cannot enter into task <ClientEventTask state=pending event=on_ready coro <function on_ready at 0x000002A55BEECE50>> while another task <Task pending name='Task-2' coro=<Kernel.dispatch_queue() running at C:\Users\33767\anaconda3\lib\site-packages\ipykernel\kernelbase.py:457> cb=[IOLoop.add_future.<locals>.<lambda>() at C:\Users\33767\anaconda3\lib\site-packages\tornado\ioloop.py:688]> is being executed.
Seems like there's a conflits between some sort of tasks, do you guys know how to solve this ?

Related

discord.py heartbeat blocked on attempt to run with asyncio.run

The main idea is to make a discord integration to the existing telegram bot written with python-telegram-bot library. So here I was thinking about running multiple coroutines with asyncio.gather and asyncio.run (I'm using python 3.10).
Right now I'm not doing anything with my existing code. Instead to avoid any possible blocking code in my main app for now I decided to write this simple program which creates a bot and just push a message to logs if message is received:
import logging as log
import asyncio
import os
import discord
from discord.ext import commands
log.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=log.DEBUG)
client = commands.Bot(command_prefix="/")
#client.event
async def on_ready():
log.info('Connected to Discord')
#client.event
async def on_message(message):
log.info("Got message")
async def start_discord():
await client.start(os.environ.get('DISCORD_TOKEN'))
async def main():
await asyncio.gather(start_discord())
asyncio.run(main())
When I start it everything looks ok, but after a while I started to get exceptions that heartbeat is blocked and WebSocket connection timed out. In addition to that none of both events are triggered no matter how many messages are sent:
2022-07-04 17:50:52,378 - discord.gateway - WARNING - Shard ID None heartbeat blocked for more than 10 seconds.
Loop thread traceback (most recent call last):
File "/mnt/d/Documents/Projects/test.py", line 28, in <module>
asyncio.run(main())
File "/usr/lib/python3.10/asyncio/runners.py", line 44, in run
return loop.run_until_complete(main)
File "/usr/lib/python3.10/asyncio/base_events.py", line 633, in run_until_complete
self.run_forever()
File "/usr/lib/python3.10/asyncio/base_events.py", line 600, in run_forever
self._run_once()
File "/usr/lib/python3.10/asyncio/base_events.py", line 1860, in _run_once
event_list = self._selector.select(timeout)
File "/usr/lib/python3.10/selectors.py", line 469, in select
fd_event_list = self._selector.poll(timeout, max_ev)
But if I replace asyncio.run(main) with asyncio.get_event_loop().run_until_complete(main()) everything starts to work correctly. I see that both events are triggered and message is received. But as I see get_event_loop is deprecated and it's suggested to use asyncio.run() from 3.10:
/mnt/d/Documents/Projects/test.py:29: DeprecationWarning: There is no current event loop
asyncio.get_event_loop().run_until_complete(main())

discord.py-Cannot send a message copy from one server to another specific server

Whenever I try to run my code I get the following error. I have rechecked my channel ID several times and also enabled Privileged Gateway Intents from discord developer panels. Bot has administrator power so that shouldn't be an issue. I am using replit as my IDE.
Please help
Ignoring exception in on_message
Traceback (most recent call last):
File "/opt/virtualenvs/python3/lib/python3.8/site-packages/discord/client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "main.py", line 28, in on_message
await general.send (**message.content + ' . ' +message.author.name)
AttributeError: 'NoneType' object has no attribute 'send'
Code for the bot is as follows:
import os
import discord
intents = discord.Intents.default()
intents.members= True
client= discord.Client( intents=intents)
#client.event
async def on_ready():
print('i am ready ')
my_secret = os.environ['TOKEN']
#client.event
async def on_message(message):
if message.author== client.user:
return
if message.content.startswith('$work'):
general = client.get_channel(849317968193912842)
await general.send (**message.content + ' . ' +message.author.name)
if message.content.startswith('tesla'):
await message.channel.send('elon musk' )
client.run(my_secret)

Discord.py - Restart Command Error - RuntimeError: Event loop is closed

I am currently working on a discord bot. I was working on the restart command.
I checked on discord to see if it work, but I get this error:
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x00000245FCC9C280>
Traceback (most recent call last):
File "C:\Users\Jerry\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 116, in __del__
self.close()
File "C:\Users\Jerry\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\Jerry\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 746, in call_soon
self._check_closed()
File "C:\Users\Jerry\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 510, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x00000245FD9BB100>
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x00000245FCC9C280>
Traceback (most recent call last):
File "C:\Users\Jerry\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 116, in __del__
File "C:\Users\Jerry\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 108, in close
File "C:\Users\Jerry\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 746, in call_soon
File "C:\Users\Jerry\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 510, in _check_closed
RuntimeError: Event loop is closed
My Code
import discord
import asyncio
from discord.ext import commands
client = commands.Bot(command_prefix='>')
client.remove_command('help')
#client.event
async def on_ready():
print('Ready')
#client.event
async def on_connect():
Online = discord.Embed(title='Online', color=discord.Color.green())
Online.set_author(name="Bot Status")
#client.event
async def on_disconnect():
Offline = discord.Embed(title='Offline', color=discord.Color.red())
Offline.set_author(name="Bot Status")
#client.command()
async def clear(ctx, amount=9999):
await ctx.send("Fetching messages...", delete_after=2.0)
await asyncio.sleep(2.0)
await ctx.send(content="Deleting messages...", delete_after=2.0)
await asyncio.sleep(2)
await ctx.channel.purge(limit=amount + 1)
await ctx.send(f"Done! {amount} message(s) deleted.", delete_after=10.0)
return
#client.command()
async def restart(ctx):
await ctx.send('Restarting...', delete_after=4.0)
await ctx.message.add_reaction('👋')
await ctx.Bot.logout()
await client.login("Token", bot=True)
await ctx.send('Done!', delete_after=5.0)
client.run('Token', bot=True, reconnect=True)
I change it but it is the same thing every time. So can someone help me figure it out? Thank for all your answers!
I use Python 3.9.1
VS Code
You can use discord.ext.commands.Bot.logout and discord.ext.commands.Bot.login,
from discord.ext import commands
#client.command()
#commands.is_owner()
async def restart(ctx):
await ctx.bot.logout()
await client.login("your_token", bot=True)

Ignoring exception in on_message in pycharm using discord.py

When I type "!hello" in my discord server my bot should say "Hello (author)"
But when i run the command this error comes up
Ignoring exception in on_message
Traceback (most recent call last):
File "C:\Users\Leo\PycharmProjects\untitled\venv\lib\site-packages\discord\client.py", line 307, in _run_event
yield from getattr(self, event)(*args, **kwargs)
File "C:/Users/Leo/PycharmProjects/untitled/Discord-bot.py", line 16, in on_message
await message.channel.send('Hello {0.author.mention}'.format(message))
AttributeError: 'Channel' object has no attribute 'send'
I dont know what to do and other things on this website dont do the same thing I did. Heres My Script:
import discord
class MyClient(discord.Client):
async def on_ready(self):
print('Logged in as')
print(self.user.name)
print(self.user.id)
print('------')
async def on_message(self, message):
# we do not want the bot to reply to itself
if message.author.id == self.user.id:
return
if message.content.startswith('/Hi'):
await message.channel.send('Hello {0.author.mention}'.format(message))
client = MyClient()
client.run('TOKENWENTHERE')
Turned out i was using discord.py version 0.64! Thanks both #Vate and #MLarionv !

Asyncio "RuntimeError: Event loop is closed"

I'm trying to make a Discord Bot and it has to check an API every minute or so and then send a message to a channel.
But for some reason, the loop breaks and ends the task.
It's my first time using asyncio and discord.py
Traceback (most recent call last):
File "bot.py", line 207, in <module>
client.loop.run_forever()
File "/usr/local/lib/python3.6/asyncio/base_events.py", line 407, in run_forever
self._check_closed()
File "/usr/local/lib/python3.6/asyncio/base_events.py", line 358, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
Task was destroyed but it is pending!
task: <Task pending coro=<my_background_task() running at bot.py:193> wait_for=<Future pending cb=[<TaskWakeupMethWrapper object at 0xb52dbd10>()]>>
The source code for the script is this one:
bot.py
Just want to have my_background_task() to run forever, or at least restart if it breaks.
Make the bot run the async task
async def bg():
for i in range(3):
print("Background tast")
await asyncio.sleep(1)
#bot.event
async def on_ready():
print("Ready!")
bot.loop.create_task(bg())

Categories