I am trying to create a program that, when it stops receiving certain requests, starts the bot and stops it when the connection is restored. But no matter how hard I try, the bot ignores the command to disable the bot, as if it does not see it, whether it is the usual await bot.close() line or the entire asynchronous function. At the same time, the code does not give any error, but stupidly continues to work further. Please help me solve the problem.
I tried the following methods: the await but.close() command and the same thing only in the function. At the same time, the code does not give any error. The bot stop code starts working only when the code itself is completed
import socket
import threading
import time
import discord
import re
import os
import json
import random
import requests
import asyncio
import string
import signal
from discord.ext import commands
last_request_time = time.time() # Время последнего запроса
bot_running = False
with open('config_test.json', 'r') as file:
config = json.load(file)
bot = commands.Bot(command_prefix=config['prefix'], intents=discord.Intents.all())
bot.remove_command('help') # Удаляем стандартную команду help
@bot.event
async def on_ready():
await bot.change_presence(status=discord.Status.dnd, activity=discord.Game("❗❗❗ Аварийный режим ❗❗❗"))
print(f'Bot is ready ✅. Logged in as {bot.user.name}')
@bot.event
async def on_message(message):
if message.author == bot.user:
return
if message.content.startswith(config['prefix']):
status = discord.Embed(
description=f"**Бот находится в АВАРИЙНОМ РЕЖИМЕ ❗! Данная проблема скоро будет устранена ⌛! Системные службы не отвечают ❌**",
color=discord.Color.red()
)
await message.channel.send(embed=status)
await bot.process_commands(message)
async def async_handle_client(conn, addr):
global last_request_time, bot_running
print(f'Подключено: {addr}')
try:
conn.settimeout(30)
data = conn.recv(1024)
if data.decode('utf-8') == '240':
print('Запрос с кодом 240 принят')
if bot_running == True:
# Пример вызова функции stop_bot из другого места в коде
await bot.close() # Остановка бота
print('Остановка бота')
bot_running = False
last_request_time = time.time()
else:
print('Принят запрос, но код не совпадает')
except socket.timeout:
print('Нет запроса')
finally:
conn.close()
def handle_client(conn, addr):
asyncio.run(async_handle_client(conn, addr))
def start_server():
host = '0.0.0.0'
port = 240
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
s.bind((host, port))
s.listen()
print(f'Сервер слушает на {host}:{port}')
while True:
conn, addr = s.accept()
client_thread = threading.Thread(target=handle_client, args=(conn, addr))
client_thread.start()
async def monitor_requests():
global last_request_time, bot_running
while True:
if time.time() - last_request_time > 30:
print('Нет запроса, запуск АВАРИЙНОГО РЕЖИМА!!!')
if bot_running == False:
await bot.start(config['token'])
bot_running = True
last_request_time = time.time()
await asyncio.sleep(1)
def shutdown(signal, frame):
print(f"Получен сигнал {signal}, завершение работы...")
asyncio.get_event_loop().create_task(bot.close())
def shutdown2(signal, frame):
asyncio.get_event_loop().create_task(bot.close())
async def stop_bot():
await bot.close()
print("Бот остановлен.")
if __name__ == '__main__':
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
signal.signal(signal.SIGINT, shutdown)
signal.signal(signal.SIGTERM, shutdown)
server_thread = threading.Thread(target=start_server)
server_thread.start()
try:
loop.run_until_complete(monitor_requests())
finally:
loop.run_until_complete(loop.shutdown_asyncgens())
loop.close()
Programma is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.