我正在尝试制作一个不和谐的机器人,我可以在其中运行特定的功能,但我不断收到错误“未关闭的客户端会话”
我希望能够定期运行“getMessage”函数,但由于某种原因它在第一次调用时有效,但在第二次调用时它给了我一个错误。我试图搞乱 asyncio,但我更改的所有内容都会导致相同或不同的错误。
这是我的代码:
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))
谢谢
我建议您使用
client.run
而不是 client.start
,因为 client.run
自动处理循环管理:
# Run the bot
def get_message():
client.run(apikey)
如果由于某种原因您需要使用
client.start
,我建议您使用 asyncio.run
在异步上下文中运行该方法:
# Run the bot
async def get_message():
async with client:
await client.start(api_key)
并在您的
main.py
文件中使用 asyncio.run
运行 get_message
函数:
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)