为什么列表追加在discord.py中不起作用?

时间:2020-11-09 08:18:21

标签: python discord.py

此代码应该可以正常工作,但是它注册了我键入.spam的第一个服务器,并且如果我在另一台服务器上运行它,它不会追加列表,而是将第一个服务器ID更改为最后一个。< / p>

async def on_message(message):
    if message.author == client.user:
        return
    if message.content.startswith('.spam'):
        global thislist
        thislist = [1, 3]
        thislist.append(message.guild.id)
        print(thislist)
        print(len(thislist))
    if message.content.startswith('.stop'):
        global s
        s = str(message.guild.id)
    await client.process_commands(message)

任何帮助将不胜感激

完整代码:

import discord, pyautogui, time
from discord.ext import commands


client = commands.Bot(command_prefix = '.')

@client.event
async def on_ready():
    print('We have logged in as {0.user}'.format(client))

@client.event
async def on_message(message):
    if message.author == client.user:
        return
    if message.content.startswith('.spam'):
        global thislist
        thislist = [message.guild.id]
        print(thislist)
        print(len(thislist))
    if message.content.startswith('.stop'):
        global s
        s = str(message.guild.id)
    await client.process_commands(message)

@client.command()
@commands.has_role('discordpy')
async def spam(ctx, *, my_id):
    print("it worked")
    time.sleep(5)
    x = 1
    y = 0
    global z
    z = 0


    while y != 1:
        if z == 1:
            z = 0
            break
        myid = str(my_id)
        await ctx.channel.send(myid + " x " +str(x))
        print(x)
        x += 1
        print(y)
        time.sleep(0.5)

@client.command()
@commands.has_role('discordpy')
async def stop(ctx):
    for x in thislist:
        print(thislist)
        if x == s:
            global z
            z = 1



@client.command()
@commands.has_role('discordpy')
async def stopbot(ctx):
    self.isrunning = False






client.run('token')

dsakfjasdfkajsdfikcmedksnjedkjnfskdjnfcjsdjkfkszidfnzsjkeudfnhszjwedfhnzsjkdefnkzsdxjfnzswdxfnwxnzksxdjnfwszexznswexnjdsnhjsdnp>

1 个答案:

答案 0 :(得分:1)

如果要追加到列表中,请在函数外部分配初始值,然后仅在函数中追加。

如果在函数中分配给列表,则所有先前的元素都将被丢弃。

thislist = [1, 3]

@client.event
async def on_message(message):
    if message.author == client.user:
        return
    if message.content.startswith('.spam'):
        thislist.append(message.guild.id)
        print(thislist)
        print(len(thislist))
    if message.content.startswith('.stop'):
        global s
        s = str(message.guild.id)
    await client.process_commands(message)