when I run my Discord bot it connects and get RuntimeError: Event loop is closed. This only occurred recently when I was trying to fix my client events not working, and added intents = discord.Intents().all() and then added that into my client initializer client = commands.Bot(command_prefix = './', intents = intents)
The specific event I was working on is an auto role feature. Here are 2 attempts I made at it
#client.event
async def on_member_join(member):
guild = client.get_guild(528767443653623818)
channel = client.get_channel(722970243252879420)
role = guild.get_role(719421779600343110)
await channel.send(f"Wow, {member} just joined the Pardi!")
await member.add_roles(role)
await channel.send(f"{member} is now a {role}")
#client.event
async def on_member_join(member):
role = get(member.guild.roles, name=ROLE)
await member.add_roles(role)
print(f"{member} is now a {role}")
Any help is appreciated :)
EDIT Been asked to post the traceback so here it is
Traceback (most recent call last):
File "dbot.py", line 184, in <module>
client.run(token)
File "C:\Users\Brandon\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\discord\client.py", line 708, in run
return future.result()
File "C:\Users\Brandon\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\discord\client.py", line 687, in runner
await self.start(*args, **kwargs)
File "C:\Users\Brandon\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\discord\client.py", line 651, in start
await self.connect(reconnect=reconnect)
File "C:\Users\Brandon\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\discord\client.py", line 586, in connect
raise PrivilegedIntentsRequired(exc.shard_id) from None
discord.errors.PrivilegedIntentsRequired: Shard ID None is requesting privileged intents that have not been explicitly enabled in the developer portal. It is recommended to go
to https://discord.com/developers/applications/ and explicitly enable the privileged intents within your application's page. If this is not possible, then consider disabling the privileged intents instead.
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x000001CB8B73DF70>
Traceback (most recent call last):
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.2032.0_x64__qbz5n2kfra8p0\lib\asyncio\proactor_events.py", line 116, in __del__
self.close()
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.2032.0_x64__qbz5n2kfra8p0\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.2032.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 719, in call_soon
self._check_closed()
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.2032.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 508, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x000001CB8B73DF70>
Traceback (most recent call last):
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.2032.0_x64__qbz5n2kfra8p0\lib\asyncio\proactor_events.py", line 116, in __del__
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.2032.0_x64__qbz5n2kfra8p0\lib\asyncio\proactor_events.py", line 108, in close
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.2032.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 719, in call_soon
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.2032.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 508, in _check_closed
RuntimeError: Event loop is closed
As the traceback says it might be error in the token you entered or the intents are not enabled
Sorry couldn't add comment because my reputation is low
Hope it might help if not just ping me up again
Related
I've been trying to make a discord bot, which worked fine until I started using cogs.
There are 3 external files: fun.py, misc.py and mod.py which contain commands which should be loaded on_ready() through:
bot.load_extension(cog)
Each of the files has the following function at the end:
async def setup(bot):
await bot.add_cog(CogName(bot))
This is my code of the bot:
import json
import json
import os
import random
import sys
import discord
from discord.ext import commands, tasks
from discord.ext.commands import Context
intents = discord.Intents.all()
if not os.path.isfile("config.json"):
sys.exit("'config.json' not found! Please add it and try again.")
else:
with open("config.json") as file:
config = json.load(file)
#tasks.loop(minutes=1.0)
async def status_task() -> None:
"""
Setup the game status task of the bot
"""
statuses = ["Made by Samxel!", "M O O N", ":D"]
await bot.change_presence(activity=discord.Game(random.choice(statuses)))
bot = commands.Bot(command_prefix=commands.when_mentioned_or(
config["prefix"]), intents=intents, help_command=None)
cogs = ['cogs.fun', 'cogs.mod', 'cogs.misc'] # 'cogs' signifies the name of the folder, 'x' signifies the file name.
#bot.event
async def on_ready():
print(f'Logged in as: {bot.user.name}')
print(f'With ID: {bot.user.id}')
for cog in cogs: # Looks for the cogs,
await bot.load_extension(cog) # Loads the cogs.
return
#bot.event
async def on_command_error(context: Context, error) -> None:
if isinstance(error, commands.CommandOnCooldown):
minutes, seconds = divmod(error.retry_after, 60)
hours, minutes = divmod(minutes, 60)
hours = hours % 24
embed = discord.Embed(
title="Hey, please slow down!",
description=f"You can use this command again in {f'{round(hours)} hours' if round(hours) > 0 else ''} {f'{round(minutes)} minutes' if round(minutes) > 0 else ''} {f'{round(seconds)} seconds' if round(seconds) > 0 else ''}.",
color=0xE02B2B
)
await context.send(embed=embed)
elif isinstance(error, commands.MissingPermissions):
embed = discord.Embed(
title="Error!",
description="You are missing the permission(s) `" + ", ".join(
error.missing_permissions) + "` to execute this command!",
color=0xE02B2B
)
await context.send(embed=embed)
elif isinstance(error, commands.BotMissingPermissions):
embed = discord.Embed(
title="Error!",
description="I am missing the permission(s) `" + ", ".join(
error.missing_permissions) + "` to fully perform this command!",
color=0xE02B2B
)
await context.send(embed=embed)
elif isinstance(error, commands.MissingRequiredArgument):
embed = discord.Embed(
title="Error!",
description=str(error).capitalize(),
color=0xE02B2B
)
await context.send(embed=embed)
raise error
bot.run(config["token"], reconnect=True)
And this is the error message I'm getting:
C:\Users\lists\PycharmProjects\MOONBOT\venv\Scripts\python.exe C:\Users\lists\PycharmProjects\MOONBOT\Test.py
2022-12-14 13:08:53 INFO discord.client logging in using static token
2022-12-14 13:08:54 INFO discord.gateway Shard ID None has connected to Gateway (Session ID: 14a697b0d7cfc70b1666d995b6c92e78).
Logged in as: M O O N
With ID: 1052180600699748402
2022-12-14 13:08:56 ERROR discord.client Ignoring exception in on_ready
Traceback (most recent call last):
File "C:\Users\lists\PycharmProjects\MOONBOT\venv\Lib\site-packages\discord\ext\commands\bot.py", line 934, in _load_from_module_spec
spec.loader.exec_module(lib) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<frozen importlib._bootstrap_external>", line 940, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "C:\Users\lists\PycharmProjects\MOONBOT\cogs\fun.py", line 8, in <module>
from Test import bot
File "C:\Users\lists\PycharmProjects\MOONBOT\Test.py", line 84, in <module>
bot.run(config["token"], reconnect=True)
File "C:\Users\lists\PycharmProjects\MOONBOT\venv\Lib\site-packages\discord\client.py", line 828, in run
asyncio.run(runner())
File "C:\Users\lists\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 186, in run
raise RuntimeError(
RuntimeError: asyncio.run() cannot be called from a running event loop
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\lists\PycharmProjects\MOONBOT\venv\Lib\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "C:\Users\lists\PycharmProjects\MOONBOT\Test.py", line 41, in on_ready
await bot.load_extension(cog) # Loads the cogs.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\lists\PycharmProjects\MOONBOT\venv\Lib\site-packages\discord\ext\commands\bot.py", line 1012, in load_extension
await self._load_from_module_spec(spec, name)
File "C:\Users\lists\PycharmProjects\MOONBOT\venv\Lib\site-packages\discord\ext\commands\bot.py", line 937, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.fun' raised an error: RuntimeError: asyncio.run() cannot be called from a running event loop
2022-12-14 13:08:56 ERROR discord.client Ignoring exception in on_ready
Traceback (most recent call last):
File "C:\Users\lists\PycharmProjects\MOONBOT\venv\Lib\site-packages\discord\ext\commands\bot.py", line 934, in _load_from_module_spec
spec.loader.exec_module(lib) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "<frozen importlib._bootstrap_external>", line 940, in exec_module
File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
File "C:\Users\lists\PycharmProjects\MOONBOT\cogs\fun.py", line 8, in <module>
from Test import bot
File "C:\Users\lists\PycharmProjects\MOONBOT\Test.py", line 84, in <module>
bot.run(config["token"], reconnect=True)
File "C:\Users\lists\PycharmProjects\MOONBOT\venv\Lib\site-packages\discord\client.py", line 828, in run
asyncio.run(runner())
File "C:\Users\lists\AppData\Local\Programs\Python\Python311\Lib\asyncio\runners.py", line 186, in run
raise RuntimeError(
RuntimeError: asyncio.run() cannot be called from a running event loop
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\lists\PycharmProjects\MOONBOT\venv\Lib\site-packages\discord\client.py", line 409, in _run_event
await coro(*args, **kwargs)
File "C:\Users\lists\PycharmProjects\MOONBOT\Test.py", line 41, in on_ready
await bot.load_extension(cog) # Loads the cogs.
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\lists\PycharmProjects\MOONBOT\venv\Lib\site-packages\discord\ext\commands\bot.py", line 1012, in load_extension
await self._load_from_module_spec(spec, name)
File "C:\Users\lists\PycharmProjects\MOONBOT\venv\Lib\site-packages\discord\ext\commands\bot.py", line 937, in _load_from_module_spec
raise errors.ExtensionFailed(key, e) from e
discord.ext.commands.errors.ExtensionFailed: Extension 'cogs.fun' raised an error: RuntimeError: asyncio.run() cannot be called from a running event loop
C:\Users\lists\PycharmProjects\MOONBOT\venv\Lib\site-packages\discord\client.py:414: RuntimeWarning: coroutine 'Client.run.<locals>.runner' was never awaited
await self.on_error(event_name, *args, **kwargs)
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
Thanks for any help!
I've tried removing the on_command_error bot event and I also tried different methods to load the cog extensions... Nothing worked.
try to bot.load_extension(cog)
without await
I am creating a discord bot in pyCharm. This is the following code I have:
# bot.py
import os
import discord
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
GUILD = os.getenv('DISCORD_GUILD')
client = discord.Client()
#client.event
async def on_ready():
for guild in client.guilds:
if guild.name == GUILD:
break
print(
f'{client.user} is connected to the following guild:\n'
f'{guild.name}(id: {guild.id})'
)
client.run(TOKEN)
When I run it the following errors are produced:
Traceback (most recent call last):
File "C:\Users\elrod\venv\lib\site-packages\discord\http.py", line 300, in static_login
data = await self.request(Route('GET', '/users/#me'))
File "C:\Users\elrod\venv\lib\site-packages\discord\http.py", line 254, in request
raise HTTPException(r, data)
discord.errors.HTTPException: 401 Unauthorized (error code: 0): 401: Unauthorized
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\elrod\OneDrive\Desktop\Assignments\CPSC\Python\HextchLibraryApp\HextechLibrary.py", line 25, in <module>
client.run(TOKEN)
File "C:\Users\elrod\venv\lib\site-packages\discord\client.py", line 723, in run
return future.result()
File "C:\Users\elrod\venv\lib\site-packages\discord\client.py", line 702, in runner
await self.start(*args, **kwargs)
File "C:\Users\elrod\venv\lib\site-packages\discord\client.py", line 665, in start
await self.login(*args, bot=bot)
File "C:\Users\elrod\venv\lib\site-packages\discord\client.py", line 511, in login
await self.http.static_login(token.strip(), bot=bot)
File "C:\Users\elrod\venv\lib\site-packages\discord\http.py", line 304, in static_login
raise LoginFailure('Improper token has been passed.') from exc
discord.errors.LoginFailure: Improper token has been passed.
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x0000022950CEF160>
Traceback (most recent call last):
File "C:\Users\elrod\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 116, in __del__
self.close()
File "C:\Users\elrod\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\elrod\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 751, in call_soon
self._check_closed()
File "C:\Users\elrod\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 1
Now, what I find interesting is this:
I can assure you that I have a .env file set up as such:
DISCORD_TOKEN={my-token-here}
DISCORD_GUILD={my-server-here}
and it is the correct information
I know this because when I take the same token out of the .env file and just paste it directly into client.run() it works without issue, but of course this is private information!
So, the issue is that my file isnt being read properly? I would disagree because in testing I find that the string in DISCORD_GUILD is being read in properly without issue
I also tried the ole turn it off and back on trick by resetting to a new token but no luck
This is my last resort to understanding this error. Does anyone know what could be causing this error and ho to fix it?
Your .env file should look like this:
# .env
DISCORD_TOKEN = ADASIUHFOAka12312jsdfhpAFDA.GnTdIh.dOU0fjmz-WhfDebLN7x8ncuGbLVWyPXNftirGA
Should not contain the {}, if you included them (taking literally as you wrote in your question).
Also, you should set your intents under Discord Developers - Applications and declare them when defining client.
So I was making discord bot and everything seemed to be successful, until I stopped programm and started getting this error (yes... kinda big):
Traceback (most recent call last):
File "C:\Users\user\PycharmProjects\DsBots\venv\lib\site-packages\discord\http.py", line 300, in static_login
data = await self.request(Route('GET', '/users/#me'))
File "C:\Users\user\PycharmProjects\DsBots\venv\lib\site-packages\discord\http.py", line 254, in request
raise HTTPException(r, data)
discord.errors.HTTPException: 401 Unauthorized (error code: 0): 401: Unauthorized
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\user\PycharmProjects\DsBots\bot.py", line 30, in <module>
client.run(TOKEN)
File "C:\Users\user\PycharmProjects\DsBots\venv\lib\site-packages\discord\client.py", line 723, in run
return future.result()
File "C:\Users\user\PycharmProjects\DsBots\venv\lib\site-packages\discord\client.py", line 702, in runner
await self.start(*args, **kwargs)
File "C:\Users\user\PycharmProjects\DsBots\venv\lib\site-packages\discord\client.py", line 665, in start
await self.login(*args, bot=bot)
File "C:\Users\user\PycharmProjects\DsBots\venv\lib\site-packages\discord\client.py", line 511, in login
await self.http.static_login(token.strip(), bot=bot)
File "C:\Users\user\PycharmProjects\DsBots\venv\lib\site-packages\discord\http.py", line 304, in static_login
raise LoginFailure('Improper token has been passed.') from exc
discord.errors.LoginFailure: Improper token has been passed.
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x0000026E2673BD90>
Traceback (most recent call last):
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 116, in __del__
self.close()
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 750, in call_soon
self._check_closed()
File "C:\Users\user\AppData\Local\Programs\Python\Python310\lib\asyncio\base_events.py", line 515, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
So I found out that the problem is in authorization, and maybe security, or maybe an error in code causes bot to logout().
I found many same questions, but many of them was asked because of undetected syntax error.
Any suggestions?...
Edit: Sorry, forgot to post code. Here it is:
import os
import discord
from dotenv import load_dotenv
load_dotenv()
TOKEN = os.getenv("DISCORD_TOKEN")
GUILD = os.getenv("DISCORD_GUILD")
client = discord.Client()
#client.event
async def on_ready():
# print(f'{client.user} has connected to Discord!')
guild = discord.utils.get(client.guilds, name=GUILD)
print(
f'{client.user} is connected to the following guild:\n'
f'{guild.name}(id: {guild.id})\n'
)
members = '\n - '.join([member.name for member in guild.members])
print(f'Guild Members:\n - {members}')
async def on_message(message):
print(message)
client.run(TOKEN)
So the problem was because I was writting my TOKEN and GUILD in .env file in {}/"" (so it looked like DISCORD_TOKEN="token" or DISCORD_TOKEN={token}). But .env file always writes variables in string type. I didn't knew that, so I was getting LoginFailure: Improper token has been passed. (thanks to Eric Jin) because of my TOKEN and GUILD was with {}.
The problem solution was very simple:
Old code (.env file):
DISCORD_TOKEN="token"
DISCORD_GUILD="guild"
New code:
DISCORD_TOKEN=token
DISCORD_GUILD=guild
(yes...)
So this worked yesterday and now its popping up alot of errors since ive tried to update do a version of discord.py that will work for slash command and continue being developed.
Here's the code:
import discord
from discord.ext import commands
from apikeys import *
client = commands.Bot(command_prefix=['!', '$', '_', '*', '$', '&'])
#client.event
async def on_ready():
print('the bot is ready!')
print('------------------')
#client.event
async def hello(ctx):
await ctx.send('Hello!')
#client.event
async def on_member_joined(member):
with open('my_image.png', 'rb') as f:
picture = discord.File(f)
channel = client.get_channel(883152435357548596)
await channel.send('Hello! Its not safe to go alone! Here take this!', file=picture)
#client.event
async def goodbye(ctx):
await ctx.send('Bye! Have a good one!')
#client.event
async def selfdestruct(ctx):
with open('explosion-boom.gif', 'rb') as f:
gif = discord.File(f)
await ctx.send('We going boom!!!', file=gif)
client.run(BOTTOKEN)
Its a rather easy bit of code to have the bot do some basic commands in discord. So I was extremally confused when it started shooting errors out in the dozens. If anyone knows what is happening here and how to fix it. Can you please explain to me what I did wrong and what the next course of action should be? I've tried moving code in and out of the document and editing my main.py but as far as I can tell I haven't done anything wrong on it
and here is what happens when I try to run the code:
Traceback (most recent call last):
File "E:\Python Projects\lib\site-packages\discord\http.py", line 349, in static_login
data = await self.request(Route('GET', '/users/#me'))
File "E:\Python Projects\lib\site-packages\discord\http.py", line 302, in request
raise HTTPException(r, data)
discord.errors.HTTPException: 401 Unauthorized (error code: 0): 401: Unauthorized
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\ccarr\PycharmProjects\pythonProject\Discord Bot\main.py", line 40, in <module>
client.run(BOTTOKEN)
File "E:\Python Projects\lib\site-packages\discord\client.py", line 631, in run
return future.result()
File "E:\Python Projects\lib\site-packages\discord\client.py", line 610, in runner
await self.start(*args, **kwargs)
File "E:\Python Projects\lib\site-packages\discord\client.py", line 573, in start
await self.login(*args)
File "E:\Python Projects\lib\site-packages\discord\client.py", line 424, in login
await self.http.static_login(token.strip())
File "E:\Python Projects\lib\site-packages\discord\http.py", line 353, in static_login
raise LoginFailure('Improper token has been passed.') from exc
discord.errors.LoginFailure: Improper token has been passed.
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x00000197FC310040>
Traceback (most recent call last):
File "C:\Users\ccarr\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 116, in __del__
self.close()
File "C:\Users\ccarr\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\ccarr\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 746, in call_soon
self._check_closed()
File "C:\Users\ccarr\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
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x00000197FC310040>
Traceback (most recent call last):
File "C:\Users\ccarr\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 116, in __del__
self.close()
File "C:\Users\ccarr\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\ccarr\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 746, in call_soon
self._check_closed()
File "C:\Users\ccarr\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
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x00000197FC310040>
Traceback (most recent call last):
File "C:\Users\ccarr\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 116, in __del__
self.close()
File "C:\Users\ccarr\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\ccarr\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 746, in call_soon
self._check_closed()
File "C:\Users\ccarr\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
Process finished with exit code 1
As a new guy to python this is very intimidating.If you need any of the other documents that show up in the error section i will be more then happy to post them for review!
Are you sure you typed correctly your discord token, and are you define "BOTTOKEN" in client.run()?
Error 401 Unauthorized:
The 401 Unauthorized Error is an HTTP response status code indicating that the request sent by the client could not be authenticatedThis means that the TOKEN you entered is not valid or has been entered incorrectly.
hi i will help you step by step:
First you have to put instead of
#client.event
async def hello
this:
#client.command()
async def hello("ctx"):
await ctx.send("hi")
or if you want to be an event try this :
#client.event
async def on_message(message):
if message.content == "hello":
await message.send("hi")
note: not all commands are events !
second help :
you just put a on_member_joined event. This event doesn't exist.. the real event is
#client.event
async def on_member_join(ctx):
with open('my_image.png', 'rb') as f:
picture = discord.File(f)
channel = client.get_channel(883152435357548596)
await channel.send('Hello! Its not safe to go alone! Here take this!', file=picture)
third help:
i really dont know what you tried to do but i will try to help you in the 2 times:
if you want to do:
an event that detect when the user leave:
#client.event
async def on_member_leave(ctx)
channel = client.get_channel("id of the channel")
await ctx.channel.send ("bye !")
and if you want that to be a command you just have to put this but not client.event but client.command() like this:
#client.command()
async def goodbye(ctx):
await ctx.send('Bye! Have a good one!')
same error you put #client.event instead of #client.command()
just put it like this:
#client.command()
async def selfdestruct(ctx):
with open('explosion-boom.gif', 'rb') as f:
gif = discord.File(f)
await ctx.send('We going boom!!!', file=gif)
and the last error (im not sure thats an error)
just put instead of client.run(BOTTOKEN) put `client.run("the token")
i want to create a Discord bot that send messages I enter in a console or generate with another piece of code (e.g. sensor data) to a channel.
I've tried with the following but after entering the second message I get a RuntimeError: Event loop is closed. Any suggestions?
import discord
def send_message(message):
token = "mydiscordbottoken"
channel_id = channelid
bot = discord.Client()
#bot.event
async def on_ready():
await bot.get_channel(channel_id).send(message)
await bot.close()
bot.run(token)
while True:
mes = input('Enter message: ')
send_message(mes)
I want to get back into my while-loop outsite the fuction after printing the message.
When running the code I get the following error:
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x00000206ABBDC940>
Traceback (most recent call last):
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1776.0_x64__qbz5n2kfra8p0\lib\asyncio\proactor_events.py", line 116, in __del__
self.close()
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1776.0_x64__qbz5n2kfra8p0\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1776.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 719, in call_soon
self._check_closed()
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1776.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 508, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x00000206ABBDC940>
Traceback (most recent call last):
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1776.0_x64__qbz5n2kfra8p0\lib\asyncio\proactor_events.py", line 116, in __del__
self.close()
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1776.0_x64__qbz5n2kfra8p0\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1776.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 719, in call_soon
self._check_closed()
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1776.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 508, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
Traceback (most recent call last):
File "C:/Users/janik/PycharmProjects/learnpython/main.py", line 19, in <module>
send_message(mes)
File "C:/Users/janik/PycharmProjects/learnpython/main.py", line 14, in send_message
bot.run(token)
File "C:\Users\janik\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\LocalCache\local-packages\Python38\site-packages\discord\client.py", line 695, in run
future = asyncio.ensure_future(runner(), loop=loop)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1776.0_x64__qbz5n2kfra8p0\lib\asyncio\tasks.py", line 669, in ensure_future
task = loop.create_task(coro_or_future)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1776.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 429, in create_task
self._check_closed()
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.8_3.8.1776.0_x64__qbz5n2kfra8p0\lib\asyncio\base_events.py", line 508, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed
sys:1: RuntimeWarning: coroutine 'Client.run.<locals>.runner' was never awaited
I'm kinda new to asycio and discord.py, just wanted to print out multiple messages to my discord server.
Thank you in advance!
You haven't quite properly set up your code correctly in that input() will freeze the code. Here is how I recommend you do it.
import discord
from discord.ext import commands
client = commands.Bot(command_prefix = "PREFIX")
#client.command()
async def sendMessage(ctx, channel: discord.TextChannel, *, message):
await channel.send(message)
client.run("TOKEN")
This makes it so you can do the command (PREFIX)sendMessage (#CHANNEL) (MESSAGE). Since you're new I'll also explain the usage of the * in the command arguments. The * allows for our message to be multiple words long so that anything after the channel is included in the message.
If you have any more questions feel free to message me either on StackOverflow or on Discord at starmoan#4269!