我很难弄清楚为什么这个错误是在我的IdleRPG机器人上造成的,每个函数在各自的文件中都工作得很好,但当它们结合在一起时,会给出下面详细的错误,有人有修复这个问题的方法吗?

import time
import datetime
import threading
import requests
import json
import getpass
import os

print()
print('-----------------------------------------------------------------------------------------------------')
print()



user = getpass.getuser()
path = (f'C:/Users/{user}/autoadventure')
if os.path.exists(path) == True:
    pass
else:
    os.mkdir(path)
boosters = input('Do you have boosters enabled? Y/N ').upper()
adv = int(input('Which adventure did you want to idle? '))
leng = adv * 3600
chng = input('Are you using a different channel than last use? Y/N: ').upper()
if chng == 'Y':
    channelid = input('Input Channel ID for discord: ')
    f = open(f'C:/Users/{user}/autoadventure/channelid.txt', 'w+')
    f.write(f'{channelid}')
    f.close()
else:
    f = open(f'C:/Users/{user}/autoadventure/channelid.txt', 'r+')
    channelid = f.read()
    f.close()
auth = input('Has your authorization key changed? Y/N: ').upper()
if auth == 'Y':
    f = open(f'C:/Users/{user}/autoadventure/authkey.txt', 'w+')
    authcode = input('Please enter your authorization key: ')
    f.write(f'{authcode}')
    f.close()
else:
    f = open(f'C:/Users/{user}/autoadventure/authkey.txt', 'r+')
    authcode = f.read()
    f.close()
if boosters == 'Y':
    leng = leng/2
convert = datetime.timedelta(seconds=leng)

# payloads

url = f'https://discord.com/api/v9/channels/{channelid}/messages'

adventure = {
    'content': f"<@424606447867789312> adventure {adv}"
}
steal = {
    'content': f"<@424606447867789312> steal"
}
pray = {
    'content': f"<@424606447867789312> pray"
}
status = {
    'content': f"<@424606447867789312> status"
}
headers = {
        'authorization': f'{authcode}'
    }

def adventure():
    global adv
    msg= []
    counter = 0
    while True:
        time.sleep(5)
        r = requests.post(url, headers=headers, data=adventure,)
        print(f'Adventure Started | Level {adv} | Length {convert}')
        time.sleep(leng)
        r = requests.post(url, headers=headers, data=status,)
        counter = counter+1
        time.sleep(2)
        r2 = requests.get(url, headers=headers,)
        info = json.loads(r2.text)
        for value in info:
            msg.append(value['content'])
        check = msg[0]
        if check == (f'You reached a new level:'):
            adv = adv+1
            print(f'You leveled up! advancing to adventure {adv}!')
        print(f'Adventure {adv} Complete!')
        print(f'You have completed {counter} adventure(s) this session!')
def pray():
    while True:
        time.sleep(10)
        r = requests.post(url, headers=headers, data=pray,)
        print(f'Pray attempted, will try again in 5 hours')
        time.sleep(18000)

def steal():
    while True:
        time.sleep(15)
        r = requests.post(url, headers=headers, data=steal,)
        print(f'Steal attempted, will try again in 1 hour')
        time.sleep(3600)

if __name__ == "__main__":
    p1 = threading.Thread(target=adventure)
    p2 = threading.Thread(target=pray)
    p3 = threading.Thread(target=steal)

    p1.start()
    p2.start()
    p3.start()

当程序运行时,它呈现给我的是:

Exception in thread Thread-1 (adventure):
Traceback (most recent call last):
  File "C:\Users\ethan\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1016, in _bootstrap_inner
    self.run()
  File "C:\Users\ethan\AppData\Local\Programs\Python\Python310\lib\threading.py", line 953, in run
    self._target(*self._args, **self._kwargs)
  File "c:\Users\ethan\Desktop\autoadventurenew.py", line 74, in adventure
    r = requests.post(url, headers=headers, data=adventure,)
  File "C:\Users\ethan\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\api.py", line 115, in post
    return request("post", url, data=data, json=json, **kwargs)
  File "C:\Users\ethan\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\api.py", line 59, in request
    return session.request(method=method, url=url, **kwargs)
  File "C:\Users\ethan\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\sessions.py", line 589, in request
    resp = self.send(prep, **send_kwargs)
  File "C:\Users\ethan\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\sessions.py", line 703, in send
    r = adapter.send(request, **kwargs)
  File "C:\Users\ethan\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\adapters.py", line 486, in send
    resp = conn.urlopen(
  File "C:\Users\ethan\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\connectionpool.py", line 703, in urlopen
    httplib_response = self._make_request(
  File "C:\Users\ethan\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\connectionpool.py", line 396, in _make_request
    conn.request_chunked(method, url, **httplib_request_kw)
  File "C:\Users\ethan\AppData\Local\Programs\Python\Python310\lib\site-packages\urllib3\connection.py", line 265, in request_chunked
    for chunk in body:
TypeError: 'function' object is not iterable

它为三个线程中的每个线程执行此操作.我是不是遗漏了什么?

推荐答案

在代码中,您定义了一个名为adventure的函数.您还使用别名adventure作为词典的名称.您正在try 使用第r = requests.post(url, headers=headers, data=adventure,)行中的词典版本.您收到的错误是因为Python无法区分同名的两个对象.实际上,通过在下面一行中定义一个同名的函数,您已经覆盖了对字典的引用.此外,这两个引用都在全局范围内.

# Dictionary variable declared here
adventure = {
    'content': f"<@424606447867789312> adventure {adv}"
}

# Function declared here
def adventure():
   ...

# Now `adventure` references the function due to global scope

解决这个问题的最快方法是将调用adventure的变量重命名,这样它就不会与任何函数名冲突(反之亦然).

Python相关问答推荐

由于瓶颈,Python代码执行太慢-寻求性能优化

将轨迹优化问题描述为NLP.如何用Gekko解决这个问题?当前面临异常:@错误:最大方程长度错误

用gekko解决的ADE方程系统突然不再工作,错误消息异常:@错误:模型文件未找到.& &

pandas DataFrame GroupBy.diff函数的意外输出

Pandas 滚动最接近的价值

为什么符号没有按顺序添加?

在含噪声的3D点网格中识别4连通点模式

未知依赖项pin—1阻止conda安装""

Maya Python脚本将纹理应用于所有对象,而不是选定对象

将标签移动到matplotlib饼图中楔形块的开始处

OpenCV轮廓.很难找到给定图像的所需轮廓

当条件满足时停止ODE集成?

不允许 Select 北极滚动?

Pandas 数据帧中的枚举,不能在枚举列上执行GROUP BY吗?

删除特定列后的所有列

如何在PythonPandas 中对同一个浮动列进行逐行划分?

为什么dict. items()可以快速查找?

高效生成累积式三角矩阵

极柱内丢失类型信息""

对于标准的原始类型注释,从键入`和`从www.example.com `?