Discord bot 运行命令两次 discord.py

Posted

技术标签:

【中文标题】Discord bot 运行命令两次 discord.py【英文标题】:Discord bot running commands twice discord.py 【发布时间】:2021-04-16 18:46:49 【问题描述】:

这是主机器人和一个 cog,所有 cog 中的所有命令在调用时都会运行两次,我知道只有 1 个机器人实例在运行,并且没有重复的命令。我什至切换了文本编辑器,并且让多个人查看了我的代码,但他们无法弄清楚需要任何帮助。谢谢。

名为 main_Bot.py 的主机器人

#imports
from cogs.database import database
import discord
import time
import random
from discord.abc import GuildChannel
from discord.embeds import Embed
from discord.ext import commands
import asyncio
import os
import json
import time
import requests
from bs4 import BeautifulSoup
from discord.ext import tasks
os.chdir(os.getcwd())




intents = discord.Intents.default()
intents.members = True 
client = commands.Bot(command_prefix="-",intents=intents)
client.remove_command("help")
client.load_extension("cogs.moderation")
client.load_extension("cogs.fun")
client.load_extension("cogs.events")
client.load_extension("cogs.eco")
client.load_extension("cogs.help")
print("loaded")




async def newServer(ctx,guild):

    role = discord.utils.get(guild.roles,name = "Muted")
   
@client.event
async def on_ready():
    #when the bot powers on
    print("Ready")
    print(discord.__version__)
    await client.change_presence(status=discord.Status.online, activity=discord.Game('Type -help'))
    clearTXT.start()
    DailyTimer.start()
    muteTime.start()




@tasks.loop(seconds=10)
async def clearTXT():
    with open("spam_detect.txt", "r+") as file:
        file.truncate(0)
@tasks.loop(seconds=60)
async def DailyTimer():
    users = await database.get_bank_data()
        
    for i in users:
            
        user = await client.fetch_user(i)
        daily_timer = users[str(user.id)]["daily_timer"]
        if daily_timer <= 0:
            users[str(user.id)]["daily"] = True
        else:
            users[str(user.id)]["daily_timer"] -= 10
@tasks.loop(seconds=60)
async def muteTime():
    users = await database.get_muted_data()
    mod_chat = client.get_channel(778671755115888670)
    print("muted Time")
    for i in users:
            print("Looped")
            user = await client.fetch_user(i)
            print(user)
            daily_timer = users[str(user.id)]["time"]
            print(daily_timer)
            if daily_timer > 0:
                users[str(i)]["time"] -= 60
                print("Munis 60")
                with open("muted_players.json", "w") as f:
                    json.dump(users,f,indent=2)  
                
                

            else:
            

                print("unmuted")
                getGuild = users[str(user.id)]["server"]
                guild = client.get_guild(getGuild)
                member = guild.get_member(user.id)
                mute_role=discord.utils.get(guild.roles, name="Muted")
                await member.remove_roles(mute_role)
            #  await deleteMuted(user)  
                with open("muted_players.json", "w") as f:
                    users.pop(str(user.id))
                    json.dump(users,f,indent=2) 
                embed = discord.Embed(description= f"✅ **member.display_name mute has run out and is now unmuted**", color=discord.Color.green())
                await mod_chat.send(embed=embed)


#run client server
client.run('' )

其中一个名为 fun.py 的 Cogs

import discord
import asyncio
from discord import client
from discord.ext import commands
import requests
from bs4 import BeautifulSoup
import random

class fun(commands.Cog):
    def __init__(self, client):

        self.client = client
    @commands.Cog.listener()
    async def on_ready(self):
        print("Fun Cog Loaded")
    
    @commands.command(name="test")
    async def test(self,ctx):
        await ctx.send("this is a test")



    @commands.command(name="embed")
    @commands.has_permissions(manage_messages=True)
    async def embed(self,ctx,channel:discord.TextChannel,title, * ,words_embed):
        person = ctx.author.display_name
        words = words_embed
        print(words)
        em = discord.Embed(title = title, color = discord.Color.dark_red())
        em.description = words
    #  em.add_field(name=person,value=words)
    # em.set_footer(text = person)
        await channel.send(embed = em)
        await ctx.message.delete()



    @commands.command(name="message")
    @commands.has_permissions(manage_messages=True)
    async def embed(self,ctx,channel:discord.TextChannel, * words_embed):

        words = ' '.join([str(words) for words in words_embed]) 
        print(words)
        await channel.send(words)
        await ctx.message.delete()

    @commands.command(name='wiki')
    async def wikipedia(self,ctx):
        a = "https://en.wikipedia.org/wiki/Special:Random"
        u = requests.get(a)
        soup = BeautifulSoup(u.content, 'html.parser')
        title = soup.find(class_ = "firstHeading").text
        title = title.replace(" ", "_")
        url = 'https://en.wikipedia.org/wiki/%s' %title
        await ctx.send(f"""Here is your random Wikipedia article! 
    title - url""")


    @commands.command(name="flip")
    async def flip(self,ctx):
        results = random.randrange(0,2)
        print(results)
        if results == 1:
            em = discord.Embed(title = f"The coin landed on Heads!", color = discord.Color.dark_blue())
            await ctx.send(embed = em)
        elif results == 0:
            em = discord.Embed(title = f"The coin landed on Tails!", color = discord.Color.dark_blue())
            await ctx.send(embed = em)

def setup(client):
    client.add_cog(fun(client))

【问题讨论】:

你确定你没有运行任何隐藏的python进程吗?检查打开任务管理器(Ctrl + Shift + Esc 是的,我确定我检查了任务管理器,然后它才运行一次,没有隐藏。 您是否使用 IDE 运行 python 文件?喜欢 vscode 还是 pycharm? 是的,我正在使用 VS Code。 尝试关闭它,并关闭任务管理器中的所有实例,如果它不起作用,请尝试重新启动您的电脑 【参考方案1】:

This reddit post提供解决方案:

如果有的话

@commands.Cog.listener()
async def on_message(..):

在您加载的任何其他 cogs 扩展中的函数, 删除线

await self.client.process_commands(message)

来自它的身体。在 cogs 加载的扩展文件中不需要它,只有在主文件中才需要。

【讨论】:

以上是关于Discord bot 运行命令两次 discord.py的主要内容,如果未能解决你的问题,请参考以下文章

“错误:未找到 FFMPEG”但应安装 FFMPEG - Discord Bot

如何使用 Discord.py Cogs 使 Discord Bot 加入语音频道并在成员加入频道时播放音频文件

Discord Bot 命令未显示

Discord Bot 无需命令即可发送消息

Discord bot命令不起作用返回错误

Discord Bot w/ Discord.py 跳线