Проблема с выбором бота через TwitchIO версии 2.8.2
Разработал консольную программу для отправки сообщений от нескольких ботов в Twitch-канал. Однако столкнулся с проблемой: при попытке отправить сообщение от разных ботов в чат отображается имя только первого бота, а не того, который фактически отправил сообщение.
from twitchio.ext import commands
import asyncio
import sys
import threading
from queue import Queue
BOTS = [
{"name": "<name_bot>", "token": "oauth:<token>", "channel": "<channel>"},
]
class BotManager:
def __init__(self):
self.active_bots = {}
self.loop = asyncio.new_event_loop()
self.message_queue = Queue()
self._running = True
async def initialize_bot(self, bot_data):
try:
print(f"Инициализация бота {bot_data['name']}...")
bot = Bot(
token=bot_data['token'],
name=bot_data['name'],
channel=bot_data['channel'],
manager=self
)
self.active_bots[bot_data['name']] = bot
await bot.start()
except Exception as e:
print(f"Ошибка при инициализации бота {bot_data['name']}: {str(e)}")
async def message_worker(self):
while self._running:
try:
bot_name, message = await asyncio.to_thread(self.message_queue.get)
if bot_name == "STOP":
break
if bot_name in self.active_bots:
await self.active_bots[bot_name].send_custom_message(message)
else:
print(f"Бот {bot_name} не активен")
except Exception as e:
print(f"Ошибка в обработчике сообщений: {str(e)}")
async def run(self):
tasks = [self.initialize_bot(bot_data) for bot_data in BOTS]
tasks.append(self.message_worker())
await asyncio.gather(*tasks)
def stop(self):
self._running = False
self.message_queue.put(("STOP", ""))
class Bot(commands.Bot):
def __init__(self, token, name, channel, manager):
super().__init__(
token=token,
prefix="!",
initial_channels=[channel]
)
self.bot_name = name
self.channel_name = channel
self.manager = manager
async def event_ready(self):
print(f"✅ Бот {self.bot_name} успешно подключен!")
print(f"User ID: {self.user_id}")
async def event_message(self, message):
try:
if not message.author or message.author.name.lower() == self.bot_name.lower():
return
except AttributeError:
return
print(f"[{self.bot_name}] {message.author.name}: {message.content}")
if message.content.startswith("!привет"):
await message.channel.send(f"Привет, {message.author.name}! Я {self.bot_name}!")
async def send_custom_message(self, text):
channel = self.get_channel(self.channel_name)
if channel:
await channel.send(text)
print(f"Бот {self.bot_name} отправил: {text}")
else:
print(f"Ошибка: канал {self.channel_name} не найден")
def console_input(manager):
while True:
try:
command = input("\nВведите команду (help для справки): ").strip()
if command.lower() == 'help':
print("\nДоступные команды:")
print("list - список всех ботов")
print("send <имя_бота> <сообщение> - отправить сообщение от имени бота")
print("exit - завершить программу")
continue
if command.lower() == 'list':
print("\nАктивные боты:")
for bot_name in manager.active_bots.keys():
print(f"- {bot_name}")
continue
if command.lower().startswith('send '):
parts = command.split(maxsplit=2)
if len(parts) < 3:
print("Ошибка: неверный формат команды. Используйте: send <бот> <сообщение>")
continue
bot_name = parts[1]
message = parts[2]
manager.message_queue.put((bot_name, message))
continue
if command.lower() == 'exit':
print("Завершение программы...")
manager.stop()
for bot in manager.active_bots.values():
asyncio.run_coroutine_threadsafe(bot.close(), manager.loop)
sys.exit(0)
except Exception as e:
print(f"Ошибка обработки команды: {e}")
def main():
manager = BotManager()
# Запускаем цикл событий в отдельном потоке
threading.Thread(target=manager.loop.run_forever, daemon=True).start()
# Запускаем ботов
asyncio.run_coroutine_threadsafe(manager.run(), manager.loop)
# Запускаем консольный ввод
console_input(manager)
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt:
print("\nПрограмма остановлена пользователем")
sys.exit(0)
send sodius_ 12345
Бот sodius_ отправил: 12345
[viniqente] sodius_: 12345
[fcoez] sodius_: 12345
send fcoez 123
Бот fcoez отправил: 123
[viniqente] sodius_: 123
[fcoez] sodius_: 123
fcoez, sodius_, viniqente - это имена всех ботов