Value tallying code dysfunctions when put into discord command

删除回忆录丶 提交于 2021-01-29 13:51:01

问题


I just coded my bot and basically it sums every user's daily guild XP from the last seven days and prints it in a list into a google sheet. There is one problem and it is that the guild XP values in the list are wrong when manually adding up, which is the guild XP from all seven days from the API JSON.

The names it prints are right, but the values are wrong, and I can't tell exactly how they are. This only happens when the code below is run in a discord command, but the code functions properly when ran in PyCharm for example.

I am not sure what is going on. My bot.py is run with tmux in Ubuntu 18.04. I know that it's not a google sheets thing because I printed the list before I used google sheets, and it's not the API either.

Do I need to rearrange my code? Something with for loops?

for count in range(len(data['guild']['members'])): # For every guild member:
    res = requests.get("https://playerdb.co/api/player/minecraft/" + data['guild']['members'][count]['uuid']) # Response from server

    if res.status_code != 200: # If it wasn't a success, continue the loop and print a message
        ctx.author.send("Error 1: Invaild name from player database API!")
        continue

    name = res.json()['data']['player']['username'] # We know it was successful if we got to this point, so it's safe to try and get data from our response
    names.append(name)

# Members' GXP
    xp = data['guild']['members'][count]['expHistory']
    xp = sum(xp.values())
    xpHist.append(xp)

# Weekly Total
wTotal = sum(xpHist)
print(xpHist)

https://pastebin.com/ijViVZn7

JSON: https://pastebin.com/FaDESA5i


回答1:


Using enumerate which will give you the index and the element itself. Using a dictionary is easier to relate the xp (value) to the name (key).

scores = {}
# For every guild member:
for count, member in enumerate(data['guild']['members']):
    res = requests.get("https://playerdb.co/api/player/minecraft/" +
                       data['guild']['members'][count]['uuid'])  # Response from server

    if res.status_code != 200:  # If it wasn't a success, continue the loop and print a message
        ctx.author.send("Error 1: Invaild name from player database API!")
        continue

    # We know it was successful if we got to this point, so it's safe to try and get data from our response
    name = res.json()['data']['player']['username']
    # Members' GXP
    xp = data['guild']['members'][count]['expHistory']

    # to record scroe with the name using dict
    scores[name] = sum(xp.values())

# Weekly Total
wTotal = sum(scores.values())
print(wTotal)
print(scores)


来源:https://stackoverflow.com/questions/63334270/value-tallying-code-dysfunctions-when-put-into-discord-command

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!