与线程相关的问题 - Python 3(Discord bot)

我试着查看这个问题,但似乎我已经做了一些我不能再自己查找的东西,所以我需要你们的帮助 . 这可能是一个相当困难的,但我真的希望有人会帮助我这个!

代码:(事先为凌乱的代码道歉)

import json, requests, threading, discord, math, random
from requests import adapters
from requests_testadapter import Resp
from discord.ext.commands import Bot

TOKEN = 'SOMETOKENIDTHATICANTREVEALANDYOUKNOWWHY'
BOT_PREFIX = ('!')
url_api = 'http://api.lambdawars.com/player/matches/list/{}'  # input the 
SteamID64
client = Bot(command_prefix=BOT_PREFIX)

@client.async_event
class LocalFileAdapter(requests.adapters.HTTPAdapter):
    def build_response_from_file(self,request,steamid):
        file_path = request.url_api.format(steamid)[7:]
        with open(file_path, 'rb') as file:
            buff = bytearray(file.read())
            resp = Resp(buff)
            r = self.build_response(request, resp)

            return r

    def send(self, request, stream=False, timeout=None, verify=True, cert=None, proxies=None):
        return self.build_response_from_file(request)

requests_session = requests.session()
requests_session.mount('file://', LocalFileAdapter())
old_response = ''
monitor_ids = []

@client.command(name='addID')
async def monitoring(steamid):
    global old_response
    monitor_ids.append(steamid)
    while True:
        await client.say("Loading results for: " + steamid + "...")
        print('Loading results for: ' + steamid)
        url_new = url_api
        response = requests_session.get(url_new.format(steamid))
        if response != old_response:
            old_response = response
        try:
            global idresponse
            idresponse = str('-\nPlayer ID {} **' + response.json()['matches'][0]['end_state'] + "** on **" +
        response.json()['matches'][0]['start_date'] + "** on map **" + response.json()['matches'][0][
            'map'] + "**. \nGame mode: **" + response.json()['matches'][0]['mode'] + "**, type: **" +
        response.json()['matches'][0]['type'] + "**. \nThe match lasted **" + str(
        math.floor(float(response.json()['matches'][0]['duration']) / 60)) + "** minutes").format(id)
        except TypeError:
            print("duration type error - bust be a number")
            # await client.say(' | '.join(god_damnit_sandern))
            await client.say(random.choice["God damnit, Sandern! That match failed to be recorded properly. " + '<:hmm:453711378067226630>',
                                       "God damnit, Sandern! He stole your match data!" + '<:hmm:453711378067226630>',
                                       "God damnit, Sandern! Your match data was not found, it's all his fault!" + '<:hmm:453711378067226630>'])
        except KeyError:
            print("Wrong SteamID64 number!")
            # await client.say('|'.join(god_damnit_sandern))
            await client.say("-"
                         "\nThis (" + steamid + ") isn't SteamID64. <:hardfacepalm:453711378272878592> "
                                           "\nCheck for typos?")
        except IndexError:
            print("This SteamID64 has no game records.")
            await client.say('-'
                         '\nThis user (' + steamid + ') has never ever played Lambda Wars online yet! <:youserious:453711378687983626>'
                                                '\nWhat a loser!')

            await client.say(idresponse)

thread = threading.Thread(target=monitoring)
thread.start()

client.run(TOKEN)

我正在研究Discord机器人 . 我们的想法是创建一个命令,即 !addID 76561197995806465 ,其中ID本身是SteamID64,用于跟踪以下页面上的API结果:http://api.lambdawars.com/player/matches/list/76561197995806465

这基本上是一个JSON结果,其中一些部分从第一位中取出(['matches'] [0] [{a key,例如“duration”或“start_date”}]) .

计划是在给出这些结果后立即自动获得结果,使用监控方法中的以下部分:

if response != old_response:
    old_response = response

它确实作为命令工作,并使Discord bot在给定SteamID64和可选数字时留言,例如1(默认值为0):

LamBOTa Wars: - Player ID 76561198223952276 lost on Sat, 16 Jun 2018 10:23:49 GMT on map hlw_breakout. Game mode: destroyhq, type: FFA. The match lasted 13 minutes

(如果你想看到这个的代码,我会发布它)

因此,当我运行我的代码时,我得到以下内容:

Exception in thread Thread-1:
Traceback (most recent call last):
  File "D:\Program Files\Python\Python3\lib\threading.py", line 916, in _bootstrap_inner
    self.run()
  File "D:\Program Files\Python\Python3\lib\threading.py", line 864, in run
self._target(*self._args, **self._kwargs)
TypeError: 'Command' object is not callable

帮助将非常感谢!

在你问之前,是的,我是一般的编程新手 . 这是我对机器人的第一次体验 .

回答(0)