如何让Python Discord单词游戏Bot自动仅在单个频道运行?
如何让Discord单词游戏Bot仅在目标频道自动生效?
问题描述
我开发了一款用于控制「单词游戏」的Discord Bot:它会读取每条消息,将消息的最后一个字母加入harfkontrol列表,同时检查消息首字母是否与上一个单词的尾字母一致,功能可正常运行,但目前会在服务器所有频道生效。我希望它能自动识别目标频道,仅在该频道内读取、处理消息,已知get_channel()方法但不想手动指定频道,请问该如何修改?
原有代码
import discord import os TOKEN = os.environ['TOKEN'] client = discord.Client() kullanilan_sozcukler=[] harfkontrol = ["a"] komutlar=["bilgi!koyunu", "liste!koyunu", "sayı!koyunu", "komutlar!koyunu"] komutmetin = "Komutlar:\n**bilgi!koyunu:** Botun ne yaptığı ve kim tarafından yapıldığı hakkında bilgi almak için.\n**liste!koyunu:** Bot kanala eklendikten sonra yazılan kelimelerin listesi.\n**sayı!koyunu:** Yukarıdaki komutun gösterdiği listedeki kelime sayısı." def son_harf(kelime): list(kelime) return kelime[-1] def ilk_harf(kelime): list(kelime) return kelime[0] def kontrol(kelime): list(kelime) if harfkontrol[-1] == kelime[0]: return True else: return False @client.event async def on_ready(): print("{0.user}".format(client), "çalıştırıldı.") @client.event async def on_message(message): msg = message.content if message.author == client.user: return if msg.startswith("bilgi!koyunu"): await message.channel.send('**Kelime Oyunu,** "Kelime Oyunu" kanalınızı yöneten bir bottur. Bot, eklendiği andan itibaren kelime oyununun kurallarına uygun oynanmasını sağlar.\n\nYapıcı:AjanSmith#4747') if msg.startswith("liste!koyunu"): sozcuk_listesi = ", ".join(kullanilan_sozcukler) await message.channel.send(f"Kullanılan sözcükler: {sozcuk_listesi}") if msg.startswith("sayı!koyunu"): uzunluk = len(kullanilan_sozcukler) await message.channel.send(f"Şimdiye kadar {uzunluk} farklı kelime kullanıldı.") if msg.startswith("komutlar!koyunu"): await message.channel.send(komutmetin) if msg in komutlar: return else: if len(list(msg)) == 1: await message.delete() await message.channel.send("Lütfen bir kelime giriniz.") elif msg in kullanilan_sozcukler: await message.delete() await message.channel.send(f"{msg} sözcüğü daha önce kullanıldı. Lütfen başka bir sözcük giriniz.") elif ilk_harf(msg) != harfkontrol[-1]: await message.delete() await message.channel.send(f"Lütfen '{harfkontrol[-1]}' ile başlayan bir kelime giriniz.") else: harfkontrol.append(son_harf((msg))) kullanilan_sozcukler.append(msg) client.run(TOKEN)
解决方案
提供三种无需手动硬编码频道ID的自动识别方案,可根据需求选择:
方案1:通过频道名称自动匹配
如果目标频道的名称是固定的(比如kelime-oyunu或单词游戏),直接在消息处理逻辑开头判断频道名称,非目标频道直接跳过:
@client.event async def on_message(message): # 定义目标频道名称,可根据实际情况修改 target_names = ["kelime-oyunu", "单词游戏"] if message.channel.name not in target_names: return # 非目标频道不处理消息 msg = message.content # 后续原有代码保持不变...
方案2:允许管理员设置目标频道(更灵活)
添加一个管理员专属的设置命令,让服务器管理员自行指定游戏频道,Bot会保存该频道ID并仅在该频道工作:
- 添加设置命令与存储逻辑
# 在全局变量区域添加 target_channel_id = None # 启动时读取已保存的频道ID try: with open("target_channel.txt", "r") as f: target_channel_id = int(f.read().strip()) except FileNotFoundError: pass # 在on_message中添加设置命令 @client.event async def on_message(message): # 未设置频道时,仅允许管理员执行设置命令 if target_channel_id is None: if msg.startswith("set-channel!koyunu"): if message.author.guild_permissions.administrator: with open("target_channel.txt", "w") as f: f.write(str(message.channel.id)) global target_channel_id target_channel_id = message.channel.id await message.channel.send(f"目标频道已设置为:{message.channel.name}") else: await message.channel.send("你没有权限执行此命令!") return # 未设置频道时,其他消息直接忽略 return # 已设置频道时,仅处理目标频道的消息 if message.channel.id != target_channel_id: return msg = message.content # 后续原有代码保持不变...
方案3:通过频道分类筛选
如果目标频道属于特定分类(比如「游戏频道」分类),可以通过分类名称判断:
@client.event async def on_message(message): # 仅在指定分类下的频道生效 if not message.channel.category or message.channel.category.name != "游戏频道": return msg = message.content # 后续原有代码保持不变...
内容的提问来源于stack exchange,提问作者Kod Hastası
相关产品推荐
相关产品推荐

