Issue
I am trying to make a discord bot where I can run a specific function, but I keep getting the error 'unclosed client session'
I want to be able to run the 'getMessage' function periodically but for some reason it works on the first call, but on the second it gives me an error. I have tried to mess around with the asyncio but everything I change results in the same or different errors.
Here is my code:
main.py:
import time
import instatools
import posterbot
tags = ''
if __name__ == '__main__':
for i in range(2):
posterbot.getMessage()
time.sleep(10)
def handleMessage(message):
pass
posterbot.py:
import discord
import asyncio
import main
intents = discord.Intents.default()
intents.message_content = True # Enable message content for intents
client = discord.Client(intents=intents)
@client.event
async def on_ready():
print(f'Logged in as {client.user.name}')
await get_first_message()
await client.close()
async def get_first_message():
guild_id = 1177834521274626118 # Replace with your guild ID
channel_id = 1177834521274626121 # Replace with your channel ID
guild = client.get_guild(guild_id)
channel = guild.get_channel(channel_id)
async for message in channel.history(limit=1, oldest_first=True):
main.handleMessage(message.content)
print(f'Earliest message: {message.content}')
break # Exit the loop after retrieving the first message
# Run the bot
def getMessage():
loop = asyncio.get_event_loop()
loop.run_until_complete(client.start(apikey))
Thanks
Solution
I recommend that you use client.run
instead of client.start
, since client.run
automatically handles loop management:
# Run the bot
def get_message():
client.run(apikey)
If for some reason you need to use client.start
, I recommend that you use asyncio.run
to run the method in an asynchronous context:
# Run the bot
async def get_message():
async with client:
await client.start(api_key)
And in your main.py
file use asyncio.run
to run the get_message
coroutine:
import time
import instatools
import posterbot
import asyncio
tags = ''
if __name__ == '__main__':
for i in range(2):
asyncio.run(posterbot.get_message())
time.sleep(10)
Answered By - Hazzu
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.