Я пишу бот Discord, используя discord.py, но он не отвечает на команды. Бот запускается успешно, появляется в сети, и команды загружаются, но ничего не происходит, когда я ввожу команды в Discord-бот просто игнорирует их.
import discord
from discord.ext import commands
from dotenv import load_dotenv
import os
from bot.commands import setup_commands
from bot.db import DB
import asyncio
load_dotenv()
TOKEN = os.getenv("DISCORD_TOKEN")
if not TOKEN:
raise ValueError("Error: The DISCORD_TOKEN environment variable is missing. Make sure that .env contains DISCORD_TOKEN=.")
intents = discord.Intents.all()
intents.messages = False # Disable unnecessary permissions
intents.guilds = True
intents.message_content = True # Enable guild-related events
# Create an instance of the bot
bot = commands.Bot(command_prefix='!', intents=intents, help_command=None)
# Create a database instance
db = DB()
@bot.event
async def on_ready():
print(f'Logged in as {bot.user}')
print(f'Commands: {list(bot.commands)}') # Output the list of commands
async def main():
await db.init() # Initialize the base before starting the bot
await setup_commands(bot, db) # Pass the same database instance to the commands
await bot.start(TOKEN)
if __name__ == '__main__':
try:
asyncio.run(main())
except KeyboardInterrupt:
print("Shutting down the bot gracefully.")
< /code>
import aiosqlite
import asyncio
from contextlib import asynccontextmanager
class DB:
def __init__(self):
self.db_path = 'tasks.db'
self.lock = asyncio.Lock()
async def init(self):
# Initializing the database.
async with self.get_db() as db:
await db.execute('''CREATE TABLE IF NOT EXISTS tasks (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER,
description TEXT,
status BOOLEAN DEFAULT 0)''')
await db.execute("CREATE INDEX IF NOT EXISTS idx_user_id ON tasks(user_id);")
await db.commit()
@asynccontextmanager
async def get_db(self):
#Context manager to manage the database connection.
conn = await aiosqlite.connect(self.db_path)
conn.row_factory = aiosqlite.Row # For easy key access
try:
yield conn
finally:
await conn.close()
async def add_task(self, user_id, description):
# Adding a new task.
try:
async with self.get_db() as db:
await db.execute("INSERT INTO tasks (user_id, description) VALUES (?, ?)",
(user_id, description))
await db.commit()
except Exception as e:
print(f"Error when adding a task: {e}")
async def get_tasks(self, user_id, limit=10, offset=0):
# Get the list of tasks with pagination.
try:
async with self.get_db() as db:
cursor = await db.execute("SELECT * FROM tasks WHERE user_id = ? LIMIT ? OFFSET ?",
(user_id, limit, offset))
return await cursor.fetchall()
except Exception as e:
print(f"Error when getting tasks: {e}")
return []
async def update_task_status(self, user_id, task_id, status):
# Updating the task status.
try:
async with self.get_db() as db:
cursor = await db.execute("SELECT id FROM tasks WHERE id = ? AND user_id = ?",
(task_id, user_id))
task = await cursor.fetchone()
if not task:
return False # Task not found
await db.execute("UPDATE tasks SET status = ? WHERE id = ? AND user_id = ?",
(status, task_id, user_id))
await db.commit()
return True # Successfully updated
except Exception as e:
print(f"Error when updating task status: {e}")
return False
async def delete_task(self, user_id, task_id):
# Deleting a task.
try:
async with self.get_db() as db:
cursor = await db.execute("SELECT id FROM tasks WHERE id = ? AND user_id = ?",
(task_id, user_id))
task = await cursor.fetchone()
if not task:
return False # Task not found
await db.execute("DELETE FROM tasks WHERE id = ? AND user_id = ?",
(task_id, user_id))
await db.commit()
return True # Successfully deleted
except Exception as e:
print(f"Error when deleting a task: {e}")
return False
< /code>
from discord.ext import commands
from .db import DB
async def setup_commands(bot, db):
#Register commands and uses the passed DB instance
@bot.command()
@commands.cooldown(1, 5, commands.BucketType.user)
async def add(ctx, *, task_desc):
await db.add_task(ctx.author.id, task_desc)
await ctx.send(f"Task added: {task_desc}")
@bot.command()
async def list(ctx):
tasks = await db.get_tasks(ctx.author.id)
if not tasks:
await ctx.send("You have no tasks!")
return
response = '\n'.join([f"{t[0]}: {t[2]} ({'✓' if t[3] else '✗'})" for t in tasks])
await ctx.send(response)
@bot.command()
async def done(ctx, task_id: str):
if not task_id.isdigit():
await ctx.send("Error: The task ID must be an integer.")
return
task_id = int(task_id)
if await db.update_task_status(ctx.author.id, task_id, True):
await ctx.send(f"Task {task_id} is complete!")
else:
await ctx.send(f"Error: Task {task_id} was not found.")
@bot.command()
async def delete(ctx, task_id: str):
if not task_id.isdigit():
await ctx.send("Error: The task ID must be an integer.")
return
task_id = int(task_id)
if await db.delete_task(ctx.author.id, task_id):
await ctx.send(f"Task {task_id} has been deleted!")
else:
await ctx.send(f"Error: Task {task_id} was not found.")
@bot.command()
async def help(ctx):
help_text = (
"**Available commands:**\n"
"`!add description' - add new task.\n"
"`!list - show all tasks.\n"
"`!done ' - mark task as done.\n"
"`!delete ' - delete task.\n"
"`!help` - show list of commands."
)
await ctx.send(help_text)
Это основные файлы, которые, как я полагаю, имеют ошибку, которую я не вижу. Список команд). < /li>
[*] Проверил, что .env содержит правильный токен. < /li>
Запустил бот с отладкой (
Я пишу бот Discord, используя discord.py, но он не отвечает на команды. Бот запускается успешно, появляется в сети, и команды загружаются, но ничего не происходит, когда я ввожу команды в Discord-бот просто игнорирует их.[code]import discord from discord.ext import commands from dotenv import load_dotenv import os from bot.commands import setup_commands from bot.db import DB import asyncio
load_dotenv() TOKEN = os.getenv("DISCORD_TOKEN")
if not TOKEN: raise ValueError("Error: The DISCORD_TOKEN environment variable is missing. Make sure that .env contains DISCORD_TOKEN=.")
# Create an instance of the bot bot = commands.Bot(command_prefix='!', intents=intents, help_command=None)
# Create a database instance db = DB()
@bot.event async def on_ready(): print(f'Logged in as {bot.user}') print(f'Commands: {list(bot.commands)}') # Output the list of commands
async def main(): await db.init() # Initialize the base before starting the bot await setup_commands(bot, db) # Pass the same database instance to the commands await bot.start(TOKEN)
if __name__ == '__main__': try: asyncio.run(main()) except KeyboardInterrupt: print("Shutting down the bot gracefully.") < /code> import aiosqlite import asyncio from contextlib import asynccontextmanager
class DB: def __init__(self): self.db_path = 'tasks.db' self.lock = asyncio.Lock()
async def init(self): # Initializing the database. async with self.get_db() as db: await db.execute('''CREATE TABLE IF NOT EXISTS tasks ( id INTEGER PRIMARY KEY AUTOINCREMENT, user_id INTEGER, description TEXT, status BOOLEAN DEFAULT 0)''') await db.execute("CREATE INDEX IF NOT EXISTS idx_user_id ON tasks(user_id);") await db.commit()
@asynccontextmanager async def get_db(self): #Context manager to manage the database connection. conn = await aiosqlite.connect(self.db_path) conn.row_factory = aiosqlite.Row # For easy key access try: yield conn finally: await conn.close()
async def add_task(self, user_id, description): # Adding a new task. try: async with self.get_db() as db: await db.execute("INSERT INTO tasks (user_id, description) VALUES (?, ?)", (user_id, description)) await db.commit() except Exception as e: print(f"Error when adding a task: {e}")
async def get_tasks(self, user_id, limit=10, offset=0): # Get the list of tasks with pagination. try: async with self.get_db() as db: cursor = await db.execute("SELECT * FROM tasks WHERE user_id = ? LIMIT ? OFFSET ?", (user_id, limit, offset)) return await cursor.fetchall() except Exception as e: print(f"Error when getting tasks: {e}") return []
async def update_task_status(self, user_id, task_id, status): # Updating the task status. try: async with self.get_db() as db: cursor = await db.execute("SELECT id FROM tasks WHERE id = ? AND user_id = ?", (task_id, user_id)) task = await cursor.fetchone() if not task: return False # Task not found await db.execute("UPDATE tasks SET status = ? WHERE id = ? AND user_id = ?", (status, task_id, user_id)) await db.commit() return True # Successfully updated except Exception as e: print(f"Error when updating task status: {e}") return False
async def delete_task(self, user_id, task_id): # Deleting a task. try: async with self.get_db() as db: cursor = await db.execute("SELECT id FROM tasks WHERE id = ? AND user_id = ?", (task_id, user_id)) task = await cursor.fetchone() if not task: return False # Task not found await db.execute("DELETE FROM tasks WHERE id = ? AND user_id = ?", (task_id, user_id)) await db.commit() return True # Successfully deleted except Exception as e: print(f"Error when deleting a task: {e}") return False < /code> from discord.ext import commands from .db import DB
async def setup_commands(bot, db): #Register commands and uses the passed DB instance
@bot.command() async def list(ctx): tasks = await db.get_tasks(ctx.author.id) if not tasks: await ctx.send("You have no tasks!") return response = '\n'.join([f"{t[0]}: {t[2]} ({'✓' if t[3] else '✗'})" for t in tasks]) await ctx.send(response)
@bot.command() async def done(ctx, task_id: str): if not task_id.isdigit(): await ctx.send("Error: The task ID must be an integer.") return task_id = int(task_id) if await db.update_task_status(ctx.author.id, task_id, True): await ctx.send(f"Task {task_id} is complete!") else: await ctx.send(f"Error: Task {task_id} was not found.")
@bot.command() async def delete(ctx, task_id: str): if not task_id.isdigit(): await ctx.send("Error: The task ID must be an integer.") return task_id = int(task_id) if await db.delete_task(ctx.author.id, task_id): await ctx.send(f"Task {task_id} has been deleted!") else: await ctx.send(f"Error: Task {task_id} was not found.")
@bot.command() async def help(ctx): help_text = ( "**Available commands:**\n" "`!add description' - add new task.\n" "`!list - show all tasks.\n" "`!done ' - mark task as done.\n" "`!delete ' - delete task.\n" "`!help` - show list of commands." ) await ctx.send(help_text)
[/code] Это основные файлы, которые, как я полагаю, имеют ошибку, которую я не вижу. Список команд). < /li> [*] Проверил, что .env содержит правильный токен. < /li> Запустил бот с отладкой ([code]logging.basicConfig(level=logging.DEBUG)[/code]). В журналах нет ошибок.>
Мой бот Telegram, созданный с использованием Python и Pyrogram, работал правильно, т. е. получал все сообщения со всех каналов, на которые подписан Telegram. Начались следующие проблемы:
Не приходят сообщения с телеграм-каналов.
Не приходят все...
Ситуация и проблема:
Я проигрываю песню и создаю список песен, которые будут воспроизводиться. После этого я использую >skip, попадаю в play_music, попадаю в self.vc.play и там запускаю после =, когда предыдущая песня закончилась из-за того, что я >...