首页 > 解决方案 > 不和谐增量不起作用

问题描述

我正在尝试在 Discord.js Python 中实现一个函数/代码,每次服务器中的用户提到数组中的一个单词时,它都会将该函数加一。因此,机器人可以计算一组单词在服务器中被说了多少次。但是,我一直遇到一个问题,即函数根本不会增加,它总是会简单地打印出“1”。

import discord;
import os
import requests
import json
import random


client = discord.Client()

word = [ hello, hi, thanks, good ]

@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
    msg = message.content

    if message.content.startswith('$commands'):
      await message.channel.send('$stats')
      await message.channel.send('$counter')
      await message.channel.send('$address')
      await message.channel.send('$csgo')
      await message.channel.send('$cpicture')

      
    if message.content.startswith('$counter'):
      increment = 0
      increment += 1
      print(increment)
      any(word in msg for word in word)
      await message.channel.send('This server has said the word ')
      await message.channel.send(increment)
      await message.channel.send(' times.')
  
client.run(os.getenv('TOKEN'))

os.environ['TOKEN']

标签: pythondiscord

解决方案


您可以尝试下面的代码,其中对其进行了三处更改。让我知道它是否有助于解决问题。请参阅代码注释以了解所做的更改。

import discord;
import os
import requests
import json
import random


client = discord.Client()
word = [ hello, hi, thanks, good ]
increment=0; #Try adding here to global scope

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

@client.event
async def on_message(message):
    global increment #Get a reference to the global variable above
    if message.author == client.user:
        return
    msg = message.content

    if message.content.startswith('$commands'):
      await message.channel.send('$stats')
      await message.channel.send('$counter')
      await message.channel.send('$address')
      await message.channel.send('$csgo')
      await message.channel.send('$cpicture')

    if message.content.startswith('$counter'):
      #increment = 0 (Remove this to prevent resetting)
      increment += 1
      print(increment)
       any(word in msg for word in word)
      await message.channel.send('This server has said the word ')
      await message.channel.send(increment)
      await message.channel.send(' times.')

client.run(os.getenv('TOKEN'))

os.environ['TOKEN']

推荐阅读