Issue
I'm using Pycord library to develop my discord bot. I'm using asyncpg
, so I do not use regular bot.run()
because it takes control over a loop and I cannot properly execute db queries, they all give Task is already in progress kind of error.
Maybe there's something wrong with my implementation of bot launch, but the first 5-10 minutes bot works fine, responding to commands and executing everything alright. Later then, bot goes offline and I only get on_ready()
event firing every 10 minutes, on_connect()
does not fire (screenshot of log attached)
After the Bot is ready! message bot goes online for 2-3 minutes and then back offline.
Here's the whole main.py script, just scroll down to the main()
function. Left event cog here in case maybe I messed up some of the events and the issue lies there.
import asyncio
import os
import sys
import discord
from database import Database
from embeds import DefaultEmbed, LinkEmbed
from environ_loader import load_env
from logger import Log
from owner_commands import OwnerCog
from twitch import TwitchRequests
from ui import LinkView
class EventCog(discord.Cog):
def __init__(self, bot):
self.bot: discord.Bot = bot
self.db: Database = None
@discord.Cog.listener()
async def on_ready(self):
self.db: Database = self.bot.db
Log.success("Bot is ready!")
@discord.Cog.listener()
async def on_connect(self):
await self.bot.sync_commands()
Log.info("Connected to the servers")
@discord.Cog.listener()
async def on_guild_join(self, guild: discord.Guild):
channel = guild.system_channel
if channel:
channel = channel.id
await self.db.add_guild(guild.id, channel)
@discord.Cog.listener()
async def on_guild_remove(self, guild: discord.Guild):
print(f"Should delete {guild.id}")
print(await self.db.remove_guild(guild.id))
async def setup_hook(self):
bot.db = await Database.connect()
perms = discord.Permissions()
intents = discord.Intents()
perms.manage_roles = True
intents.guilds = True
bot = discord.Bot(permissions=perms, intents=intents, debug_guilds=[696434683730329713])
@bot.slash_command(description="For sure!")
async def link(
ctx: discord.ApplicationContext,
twitch_url: discord.Option(str, "Enter the twitch streamer link")
):
try:
data = await TwitchRequests.getChannelInfo(twitch_url)
except Exception as e:
Log.failure(str(e))
else:
await ctx.respond(embed=LinkEmbed(
twitch_name=data["login"],
twitch_description=data["description"],
twitch_thumbnail=data["profile_image_url"],
creation_date=data["created_at"],
is_partner=data["broadcaster_type"] == "partner"
), view=LinkView())
async def main():
events = EventCog(bot)
ownerCommands = OwnerCog(bot)
bot.add_cog(events)
bot.add_cog(ownerCommands)
await bot.login(os.getenv("BOT_TOKEN"))
await bot.application_info()
DefaultEmbed.bot_name = bot.user.name
DefaultEmbed.bot_thumnail_url = bot.user.avatar.url
await events.setup_hook()
await bot.connect()
if __name__ == "__main__":
load_env()
TwitchRequests.init()
if os.name == "nt":
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
Log.info("Launching discord bot")
try:
asyncio.run(main())
print("COMPLETED")
finally:
if sys.exc_info()[0] is None:
Log.info("Bot offline")
UPDATE
Even that I said i cannot use regular bot.run()
, I tested it and it went fine, it didn't disconnect, I guess the answer lies in bot.run()
implementation. I did something wrong in my main()
coroutine. The next this is to figure out what exactly i did wrong.
Solution
Problem solved!
Bot
is inherited from Client
, which accepts loop
in init method. If it is not passed, it will create a new event loop, which will interfere with my snippet of code somehow and create those annoying periodical connects/disconnects.
So, the solution is to create a loop before bot initialization and pass current loop in discord.Bot()
constructor like so:
discord.Bot(permissions=perms, intents=intents, debug_guilds=[...], loop=loop)
P.S:
It also solved a problem with autocomplete in slash commands. Before I couldn't do anything because it was constantly saying that the bot loop and loop where the command was executed are different. Now it's working perfectly fine and even better! =)
Answered By - Andrew
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.