K
K
KeySh1e2020-08-22 22:12:24
Python
KeySh1e, 2020-08-22 22:12:24

Tasks.loop hangs in cogs, what should I do?

Good evening, I wrote the following code:

import discord
from discord.ext import commands, tasks

import valve.rcon
import valve.source.a2s


class Check(commands.Cog):

    def __init__(self, client, address, password):
        self.client = client
        self.address = address
        self.password = password
        self.check.start()


    @tasks.loop(seconds=10)
    async def check(self):
        try:
            with valve.source.a2s.ServerQuerier(self.address, timeout=10.0) as server:
                info = server.info()
                players = info['player_count']
                max_players = info['max_players']
                print(f"-----------------------------------\n"
                      f"Player count: {players}/{max_players}")
            if players == 0:
                await self.client.change_presence(status=discord.Status.idle,
                                             activity=discord.Game(f"{players}/{max_players}"))
            else:
                await self.client.change_presence(status=discord.Status.online,
                                             activity=discord.Game(f"{players}/{max_players}"))
        except valve.source.NoResponseError:
            print(f"-----------------------------------\n"
                  f"Server dead")
            await self.client.change_presence(status=discord.Status.dnd,
                                         activity=discord.Game("Ислам"))


This code, every 10 seconds, requests information from the CS:GO server. It is working, but after a while +- a couple of hours, it just stops working, and you have to restart the bot. I tried to do it through the hosting apish, but the result is the same, I suspect that I didn’t do tasks.loop correctly (Made in cog). Thank you in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
shurshur, 2020-08-23
@shurshur

Why do it in Cog? We just create a function with the @tasks.loop decorator, and then run it:

@task.loop(seconds=10)
async def cool_task():
  do_something_awesome

cool_task.start()
bot.run(TOKEN)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question