Error with on reaction add, How to resolve this? - python

Code Example
#client.event
async def on_reaction_add(reaction, user):
channel = reaction.message.channel
if reaction.emoji == '🇪🇸':
translaty = translator.translate(
str(reaction.message.content), lang_tgt='es')
await channel.send("Translating {}'s message: {}".format(str(reaction.message.author)[:-5], reaction.message.content))
await channel.send("`" + str(translaty) + "`")
The current code was working however i am not getting the following error.
Ignoring exception in on_reaction_add
Traceback (most recent call last):
File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\site-packages\discord\client.py", line 343, in _run_event
await coro(*args, **kwargs)
File "C:\Users\Dell\Desktop\discordbotpy\bot.py", line 29, in on_reaction_add
translaty = translator.translate(
File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\site-packages\google_trans_new\google_trans_new.py", line 188, in translate
raise e
File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\site-packages\google_trans_new\google_trans_new.py", line 152, in translate
response = json.loads(response)
File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\json\__init__.py", line 346, in loads
return _default_decoder.decode(s)
File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\json\decoder.py", line 340, in decode
raise JSONDecodeError("Extra data", s, end)
json.decoder.JSONDecodeError: Extra data: line 1 column 970 (char 969)
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x000001D99233E040>
Traceback (most recent call last):
File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 116, in __del__
File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\asyncio\proactor_events.py", line 108, in close
File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 746, in call_soon
File "C:\Users\Dell\AppData\Local\Programs\Python\Python39\lib\asyncio\base_events.py", line 510, in _check_closed
Any help would be greatly appreciated, my mind has just gone blank and cannot seem to work it out. As I stated above this worked about 1 week ago and i have not touched the code since, but now I just get the above error.

I think you're suffering from an unfortunate error with the google translate library you're using to translate the message.
Had a quick look online and someone's already posted a workaround here

Related

TelegramAPIError: Bad Gateway (aiogram)

I create a bot that notifies the user at certain times, but from time to time gives this error
dispatcher.py [LINE:390] ERROR | 2022-10-03 04:10:16,846 : Cause exception while getting updates.
Traceback (most recent call last):
File "/usr/local/lib/python3.8/dist-packages/aiogram/dispatcher/dispatcher.py", line 381, in start_polling
updates = await self.bot.get_updates(
File "/usr/local/lib/python3.8/dist-packages/aiogram/bot/bot.py", line 110, in get_updates
result = await self.request(api.Methods.GET_UPDATES, payload)
File "/usr/local/lib/python3.8/dist-packages/aiogram/bot/base.py", line 231, in request
return await api.make_request(await self.get_session(), self.server, self.__token, method, data, files,
File "/usr/local/lib/python3.8/dist-packages/aiogram/bot/api.py", line 140, in make_request
return check_result(method, response.content_type, response.status, await response.text())
File "/usr/local/lib/python3.8/dist-packages/aiogram/bot/api.py", line 128, in check_result
raise exceptions.TelegramAPIError(description)
aiogram.utils.exceptions.TelegramAPIError: Bad Gateway
I think this problem is on the telegram side itself and is solved via webhook, but I don't want to use them.

What could be causing this error: RuntimeError('Event loop is closed') in Python

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.

Issue when user clicks Adaptive Card to invoke Task Module in the channel

When the user clicks on the Adaptive Card to invoke Task Module in the iOS Teams client, there is an error. The Adaptive Card works well with other types of clients, like Mac, and Browsers.
Steps to reproduce the error:
Bot sent the following Adaptive Card to a channel according to the user's input.
{
"type":"AdaptiveCard",
"$schema":"http://adaptivecards.io/schemas/adaptive-card.json",
"version":"1.3",
"fallbackText":"This card requires Adaptive Cards v1.2 support to be rendered properly.",
"body":[
{
"type":"ColumnSet",
"columns":[
{
"type":"Column",
"items":[
{
"type":"TextBlock",
"text":"**Query:**",
"size":"Medium",
"weight":"Bolder",
"wrap":false
}
],
"width":"48px"
},
{
"type":"Column",
"items":[
{
"type":"TextBlock",
"text":"sales today",
"size":"Medium",
"wrap":true
}
],
"width":"auto"
}
]
},
{
"type":"Container",
"id":"table",
"items":[
{
"type":"Container",
"bleed":true,
"items":[
{
"type":"ColumnSet",
"columns":[
{
"type":"Column",
"width":"auto",
"bleed":true,
"items":[
{
"type":"TextBlock",
"text":"No Data Found: We understood what you meant, however we didn't find any data matching your query. If you believe this is an error, please **report** this issue.",
"horizontalAlignment":"left",
"wrap":"true"
}
],
"selectAction":{
"type":"Action.Submit",
"title":"column",
"data":{
"msteams":{
"type":"task/fetch"
},
"action_source":"report_issue",
"id":"report_issue_invoke",
"message_type":"no_data_found",
"message":"No data found",
"query_id":"q_7aGLqUYvSEWw1rjAbBiXMw",
"user_id":"29:18Ly6dqUHd5j1HwXtx7z8qsndhqYOSc22UzQehulpOcIHLUcXAoJR0w2evYTwhFHFXaG5fEyYrZwFHZyO0PqRdQ"
}
}
}
]
}
]
}
]
}
]
}
The user can click on the text to invoke a Task Module dialogue to fill in the feedback content. Then there will be an error thrown out if the user is using the iOS Teams client(Other types of clients are working well, like Mac, Android, and Chrome, Firefox, Safari browsers):
Following is the error stack:
/Users/liming/venv/autoql-teams-bot/bin/python3.9 /Users/liming/Dev/Projects/chata/autoql-teams-bot/app.py
Running in Dev configuration
current env is:DEV
APP_ID is:acec457a-326b-43f1-9b38-724baaeb0057
======== Running on http://localhost:3978 ========
(Press CTRL+C to quit)
[on_turn_error] unhandled error: Unable to deserialize to object: type, AttributeError: 'str' object has no attribute 'get'
Traceback (most recent call last):
File "/Users/liming/venv/autoql-teams-bot/lib/python3.9/site-packages/msrest/serialization.py", line 1293, in _deserialize
found_value = key_extractor(attr, attr_desc, data)
File "/Users/liming/venv/autoql-teams-bot/lib/python3.9/site-packages/msrest/serialization.py", line 1064, in rest_key_extractor
return working_data.get(key)
AttributeError: 'str' object has no attribute 'get'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/liming/venv/autoql-teams-bot/lib/python3.9/site-packages/botbuilder/core/bot_adapter.py", line 128, in run_pipeline
return await self._middleware.receive_activity_with_status(
File "/Users/liming/venv/autoql-teams-bot/lib/python3.9/site-packages/botbuilder/core/middleware_set.py", line 69, in receive_activity_with_status
return await self.receive_activity_internal(context, callback)
File "/Users/liming/venv/autoql-teams-bot/lib/python3.9/site-packages/botbuilder/core/middleware_set.py", line 91, in receive_activity_internal
raise error
File "/Users/liming/venv/autoql-teams-bot/lib/python3.9/site-packages/botbuilder/core/middleware_set.py", line 89, in receive_activity_internal
return await next_middleware.on_turn(context, call_next_middleware)
File "/Users/liming/venv/autoql-teams-bot/lib/python3.9/site-packages/botbuilder/core/show_typing_middleware.py", line 96, in on_turn
result = await logic()
File "/Users/liming/venv/autoql-teams-bot/lib/python3.9/site-packages/botbuilder/core/middleware_set.py", line 84, in call_next_middleware
return await self.receive_activity_internal(
File "/Users/liming/venv/autoql-teams-bot/lib/python3.9/site-packages/botbuilder/core/middleware_set.py", line 79, in receive_activity_internal
return await callback(context)
File "/Users/liming/Dev/Projects/chata/autoql-teams-bot/bots/dialog_bot.py", line 42, in on_turn
await super().on_turn(turn_context)
File "/Users/liming/venv/autoql-teams-bot/lib/python3.9/site-packages/botbuilder/core/activity_handler.py", line 78, in on_turn
invoke_response = await self.on_invoke_activity(turn_context)
File "/Users/liming/venv/autoql-teams-bot/lib/python3.9/site-packages/botbuilder/core/teams/teams_activity_handler.py", line 154, in on_invoke_activity
deserializer_helper(
File "/Users/liming/venv/autoql-teams-bot/lib/python3.9/site-packages/botbuilder/core/serializer_helper.py", line 28, in deserializer_helper
return deserializer(msrest_cls.__name__, dict_to_deserialize)
File "/Users/liming/venv/autoql-teams-bot/lib/python3.9/site-packages/msrest/serialization.py", line 1233, in __call__
return self._deserialize(target_obj, data)
File "/Users/liming/venv/autoql-teams-bot/lib/python3.9/site-packages/msrest/serialization.py", line 1299, in _deserialize
value = self.deserialize_data(raw_value, attr_desc['type'])
File "/Users/liming/venv/autoql-teams-bot/lib/python3.9/site-packages/msrest/serialization.py", line 1468, in deserialize_data
return self._deserialize(obj_type, data)
File "/Users/liming/venv/autoql-teams-bot/lib/python3.9/site-packages/msrest/serialization.py", line 1303, in _deserialize
raise_with_traceback(DeserializationError, msg, err)
File "/Users/liming/venv/autoql-teams-bot/lib/python3.9/site-packages/msrest/exceptions.py", line 51, in raise_with_traceback
raise error.with_traceback(exc_traceback)
File "/Users/liming/venv/autoql-teams-bot/lib/python3.9/site-packages/msrest/serialization.py", line 1293, in _deserialize
found_value = key_extractor(attr, attr_desc, data)
File "/Users/liming/venv/autoql-teams-bot/lib/python3.9/site-packages/msrest/serialization.py", line 1064, in rest_key_extractor
return working_data.get(key)
msrest.exceptions.DeserializationError: Unable to deserialize to object: type, AttributeError: 'str' object has no attribute 'get'
Traceback (most recent call last):
File "/Users/liming/venv/autoql-teams-bot/lib/python3.9/site-packages/msrest/serialization.py", line 1293, in _deserialize
found_value = key_extractor(attr, attr_desc, data)
File "/Users/liming/venv/autoql-teams-bot/lib/python3.9/site-packages/msrest/serialization.py", line 1064, in rest_key_extractor
return working_data.get(key)
AttributeError: 'str' object has no attribute 'get'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/liming/venv/autoql-teams-bot/lib/python3.9/site-packages/botbuilder/core/bot_adapter.py", line 128, in run_pipeline
return await self._middleware.receive_activity_with_status(
File "/Users/liming/venv/autoql-teams-bot/lib/python3.9/site-packages/botbuilder/core/middleware_set.py", line 69, in receive_activity_with_status
return await self.receive_activity_internal(context, callback)
File "/Users/liming/venv/autoql-teams-bot/lib/python3.9/site-packages/botbuilder/core/middleware_set.py", line 91, in receive_activity_internal
raise error
File "/Users/liming/venv/autoql-teams-bot/lib/python3.9/site-packages/botbuilder/core/middleware_set.py", line 89, in receive_activity_internal
return await next_middleware.on_turn(context, call_next_middleware)
File "/Users/liming/venv/autoql-teams-bot/lib/python3.9/site-packages/botbuilder/core/show_typing_middleware.py", line 96, in on_turn
result = await logic()
File "/Users/liming/venv/autoql-teams-bot/lib/python3.9/site-packages/botbuilder/core/middleware_set.py", line 84, in call_next_middleware
return await self.receive_activity_internal(
File "/Users/liming/venv/autoql-teams-bot/lib/python3.9/site-packages/botbuilder/core/middleware_set.py", line 79, in receive_activity_internal
return await callback(context)
File "/Users/liming/Dev/Projects/chata/autoql-teams-bot/bots/dialog_bot.py", line 42, in on_turn
await super().on_turn(turn_context)
File "/Users/liming/venv/autoql-teams-bot/lib/python3.9/site-packages/botbuilder/core/activity_handler.py", line 78, in on_turn
invoke_response = await self.on_invoke_activity(turn_context)
File "/Users/liming/venv/autoql-teams-bot/lib/python3.9/site-packages/botbuilder/core/teams/teams_activity_handler.py", line 154, in on_invoke_activity
deserializer_helper(
File "/Users/liming/venv/autoql-teams-bot/lib/python3.9/site-packages/botbuilder/core/serializer_helper.py", line 28, in deserializer_helper
return deserializer(msrest_cls.__name__, dict_to_deserialize)
File "/Users/liming/venv/autoql-teams-bot/lib/python3.9/site-packages/msrest/serialization.py", line 1233, in __call__
return self._deserialize(target_obj, data)
File "/Users/liming/venv/autoql-teams-bot/lib/python3.9/site-packages/msrest/serialization.py", line 1299, in _deserialize
value = self.deserialize_data(raw_value, attr_desc['type'])
File "/Users/liming/venv/autoql-teams-bot/lib/python3.9/site-packages/msrest/serialization.py", line 1468, in deserialize_data
return self._deserialize(obj_type, data)
File "/Users/liming/venv/autoql-teams-bot/lib/python3.9/site-packages/msrest/serialization.py", line 1303, in _deserialize
raise_with_traceback(DeserializationError, msg, err)
File "/Users/liming/venv/autoql-teams-bot/lib/python3.9/site-packages/msrest/exceptions.py", line 51, in raise_with_traceback
raise error.with_traceback(exc_traceback)
File "/Users/liming/venv/autoql-teams-bot/lib/python3.9/site-packages/msrest/serialization.py", line 1293, in _deserialize
found_value = key_extractor(attr, attr_desc, data)
File "/Users/liming/venv/autoql-teams-bot/lib/python3.9/site-packages/msrest/serialization.py", line 1064, in rest_key_extractor
return working_data.get(key)
msrest.exceptions.DeserializationError: Unable to deserialize to object: type, AttributeError: 'str' object has no attribute 'get'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "/Users/liming/venv/autoql-teams-bot/lib/python3.9/site-packages/botbuilder/core/integration/aiohttp_channel_service_exception_middleware.py", line 20, in aiohttp_error_middleware
response = await handler(request)
File "/Users/liming/Dev/Projects/chata/autoql-teams-bot/app.py", line 158, in messages
invoke_response = await CONFIG.ADAPTER.process_activity(activity, auth_header, BOT.on_turn)
File "/Users/liming/venv/autoql-teams-bot/lib/python3.9/site-packages/botbuilder/core/bot_framework_adapter.py", line 451, in process_activity
return await self.process_activity_with_identity(activity, identity, logic)
File "/Users/liming/venv/autoql-teams-bot/lib/python3.9/site-packages/botbuilder/core/bot_framework_adapter.py", line 493, in process_activity_with_identity
await self.run_pipeline(context, logic)
File "/Users/liming/venv/autoql-teams-bot/lib/python3.9/site-packages/botbuilder/core/bot_adapter.py", line 133, in run_pipeline
await self.on_turn_error(context, error)
File "/Users/liming/Dev/Projects/chata/autoql-teams-bot/app.py", line 111, in on_error
await utilities.send_message_with_log(context, Activity("The bot encountered an error or bug."))
TypeError: __init__() takes 1 positional argument but 2 were given
Scenario 1: It displays an error: "Something went wrong. Please try again"
Scenario 2: It displays an error: "Something went wrong. Please try again"
The root cause is the data transferred from iOS client contain a parameter “tab_entity_id” with 0 length string value to the bot. This value will cause the error AttributeError: 'str' object has no attribute 'get' This error/exception was thrown out inside MS python library file msrest/serialzation.py, before the logic goes into our bot.
This error comes before the logic entering the bot. We are not able to fix it.
The file serialization.py is part of package msrest. The msrest package is provided by MS for Azure:
https://learn.microsoft.com/en-us/python/api/msrest/msrest.serialization?view=azure-python
file serialization.py
Here are the screenshots:
This screenshot shows the exception was thrown out at line 1064 in file serialization.py in the console.
the exception was thrown out at line 1064 in file serialization.py
This screenshot shows the parameter value is 0 size string just before the exception was generated in line 1064 in file serialization.py
the parameter value is 0 size string just before the exception was generated in line 1064 in file serialization.py
This screenshot shows the value of “tab_entity_id” from iOS client is 0 length string.
the value of “tab_entity_id” from iOS client is 0 length string
I confirmed this issue can be reproduced by BotBuilder python library in 4.12.0(when we found this issue first time), 4.14.0(currently version in PROD) and 4.14.2(the latest released version for today, April 27, 2022). This issue still can be reproduced in latest version 4.14.2. Here is the link about the most recently release version information.
https://github.com/microsoft/botbuilder-python

TypeError: Object of type Translated is not JSON serializable - Discord.py Bot

I tried to make a simple translate funcion in my Discord Bot and got to this Error:
Ignoring exception in command translate:
Traceback (most recent call last):
File "C:\Users\Luca\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 85, in wrapped
ret = await coro(*args, **kwargs)
File "c:\Users\Luca\Documents\Discord\cogs\translate.py", line 30, in translate
await msg.send(embed=new_emd, delete_after=20)
File "C:\Users\Luca\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\abc.py", line 904, in send
data = await state.http.send_message(channel.id, content, tts=tts, embed=embed,
File "C:\Users\Luca\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\http.py", line 156, in request
kwargs['data'] = utils.to_json(kwargs.pop('json'))
File "C:\Users\Luca\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\utils.py", line 318, in to_json
return json.dumps(obj, separators=(',', ':'), ensure_ascii=True)
File "C:\Users\Luca\AppData\Local\Programs\Python\Python38\lib\json\__init__.py", line 234, in dumps
return cls(
File "C:\Users\Luca\AppData\Local\Programs\Python\Python38\lib\json\encoder.py", line 199, in encode
chunks = self.iterencode(o, _one_shot=True)
File "C:\Users\Luca\AppData\Local\Programs\Python\Python38\lib\json\encoder.py", line 257, in iterencode
return _iterencode(o, 0)
File "C:\Users\Luca\AppData\Local\Programs\Python\Python38\lib\json\encoder.py", line 179, in default
raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type Translated is not JSON serializable
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\Luca\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\bot.py", line 903, in invoke
await ctx.command.invoke(ctx)
File "C:\Users\Luca\AppData\Local\Programs\Python\Python38\lib\site-packages\discord\ext\commands\core.py", line 859, in invoke
await injected(*ctx.args, **ctx.kwargs)
File "C:\Users\Luca\AppData\Local\Programs\Python\Python38\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: Object of type Translated is not JSON serializable
I already looked it up, but i found no solutions. Because it is in the library i don't know what to do about it. Please help me.
This is the code i wrote:
from googletrans import Translator
import discord
from discord.ext import commands
#commands.command(pass_context=True)
async def translate(self, msg, lang, *,args):
"""Translates words from one language to another.
Usage:
-translate 'language' 'text'
Language example: 'fr' 'en'
"""
#To Check if it has the delete Messages Permission
try:await msg.message.delete()
except:
embed = discord.Embed(
colour=discord.Colour(0x1))
embed.add_field(name="I don't have the permissions to do that!",
value="please give me the 'Manage Messages' permission")
return await msg.send(embed=embed, delete_after=30)
#Simple Translator | Read on the googletrans page
t = Translator(service_urls=['translate.google.com'])
text = t.translate(args, dest=lang)
#Posts Embed with the Text and also the Language
new_emd = discord.Embed(title="Broski Translator in " + lang, description=text, colour=discord.Colour(0x1))
await msg.send(embed=new_emd, delete_after=20)
This seems to be a recurring error in googletrans package.
In this answer by #Maldus you can see a work-around to fix this issue.
Or you can try installing the new alpha version which is supposed to correct this:
pip install googletrans==3.1.0a0

discord.py - mutliple messages posting - RuntimeError: Event loop is closed

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!

Categories

Resources