Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/348.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 需要类似字节的对象,而不是';元组';尝试使用Discord bot时出错_Python_Python 3.x - Fatal编程技术网

Python 需要类似字节的对象,而不是';元组';尝试使用Discord bot时出错

Python 需要类似字节的对象,而不是';元组';尝试使用Discord bot时出错,python,python-3.x,Python,Python 3.x,我一直在编写以下Python 3代码: import urllib.request import discord import asyncio #Colors black = "\033[0;30m" red = "\033[0;31m" green = "\033[0;32m" yellow = "\033[0;33m" blue = "\033[0;34m" purple = "\033[0;35m" cyan = "\033[0;36m" white = "\033[0;37m" #B

我一直在编写以下Python 3代码:

import urllib.request
import discord
import asyncio

#Colors
black = "\033[0;30m"
red = "\033[0;31m"
green = "\033[0;32m"
yellow = "\033[0;33m"
blue = "\033[0;34m"
purple = "\033[0;35m"
cyan = "\033[0;36m"
white = "\033[0;37m"

#Bold Colors
bblack = "\033[1;30m"
bred = "\033[1;31m"
bgreen = "\033[1;32m"
byellow = "\033[1;33m"
bblue = "\033[1;34m"
bpurple = "\033[1;35m"
bcyan = "\033[1;36m"
bwhite = "\033[1;37m"

print(""""""+blue+"""  ____  _                       _  """+red+""" _____              
"""+blue+""" |  _ \(_)___  ___ ___  _ __ __| | """+red+"""|__  /___ _ __ ___  
"""+blue+""" | | | | / __|/ __/ _ \| '__/ _` | """+red+"""  / // _ \ '__/ _ \ 
"""+blue+""" | |_| | \__ \ (_| (_) | | | (_| | """+red+""" / /|  __/ | | (_) |
"""+blue+""" |____/|_|___/\___\___/|_|  \__,_|"""+red+""" /____\___|_|  \___/
""")

yes = ['y','Y','yes','Yes','YES']

email = input(bgreen+'Discord Email Address: '+yellow)
password = input(bgreen+'Discord Password: '+yellow)
hg_api = str(input(bcyan+'Hologram.io API Key: '+yellow))
hg_deviceid = int(input(bcyan+'Hologram.io Device ID: '+yellow))
sender = input(bcyan+'Sender Phone number (leave blank for default: +1-000-000-0001): '+yellow)
if sender == '':
    sender = "+1-000-000-0001"
logs = input(bpurple+'Enable console logs [Y/N]: '+yellow)
print(white)

client = discord.Client()

@client.event
async def on_ready():
    print(green+'Logged in as: '+cyan+client.user.name+white+' '+yellow+'('+client.user.id+')'+white)

@client.event
async def on_message(message):
    author = str(message.author)
    if logs in yes:
        print(yellow+"["+str(message.timestamp)[11:16]+"] "+red+author+": "+cyan+message.content+white)
    if message.author.id != client.user.id:
        body = '['+str(message.timestamp)[11:16]+'] '+author+': '+message.content
        body = str(body)
        print(body)
        values = """
          {
            "deviceid": """,hg_deviceid,""",
            "fromnumber": """,sender,""",
            "body": """,body,"""
          }
        """

        headers = {
          'Content-Type': 'application/json'
        }

        #try:
        request = urllib.request.Request('https://dashboard.hologram.io/api/1/sms/incoming?apikey='+hg_api, data=values, headers=headers)
        response_body = urllib.request.urlopen(request).read()
        #except:
        #   print(red+"Failed to login. Message not sent."+white)

client.run(email, password)
当我运行它时,会出现以下错误:

Logged in as: Coto (234246004424179712)
[21:01] EmojiGuy#7257: Either spoopy the bot is dead or it has a check then I guess
[21:01] EmojiGuy#7257: Either spoopy the bot is dead or it has a check then I guess
Ignoring exception in on_message
Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 1190, in do_request_
    mv = memoryview(data)
TypeError: memoryview: a bytes-like object is required, not 'tuple'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/discord/client.py", line 307, in _run_event
    yield from getattr(self, event)(*args, **kwargs)
  File "DiscordZero.py", line 73, in on_message
    response_body = urllib.request.urlopen(request).read()
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 163, in urlopen
    return opener.open(url, data, timeout)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 464, in open
    req = meth(req)
  File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py", line 1195, in do_request_
    data))
ValueError: Content-Length should be specified for iterable data of type <class 'tuple'> ('\n\t\t  {\n\t\t    "deviceid": ', 108749, ',\n\t\t    "fromnumber": ', '+1-000-000-0001', ',\n\t\t    "body": ', '[21:01] EmojiGuy#7257: Either spoopy the bot is dead or it has a check then I guess', '\n\t\t  }\n\t\t')
以Coto(23424604424179712)的身份登录
[21:01]EmojiGuy#7257:我猜要么是Spopy机器人死了,要么是它有支票
[21:01]EmojiGuy#7257:我猜要么是Spopy机器人死了,要么是它有支票
忽略on_消息中的异常
回溯(最近一次呼叫最后一次):
do_request中的文件“/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py”,第1190行_
mv=存储器视图(数据)
TypeError:memoryview:需要类似字节的对象,而不是“元组”
在处理上述异常期间,发生了另一个异常:
回溯(最近一次呼叫最后一次):
文件“/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site packages/discord/client.py”,第307行,在运行事件中
getattr(自身,事件)的收益率(*args,**kwargs)
on_消息中第73行的文件“DiscordZero.py”
response_body=urllib.request.urlopen(request.read)()
urlopen中的文件“/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py”,第163行
返回opener.open(url、数据、超时)
打开文件“/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py”,第464行
req=甲基(req)
do_request中的文件“/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/urllib/request.py”,第1195行_
(数据)
ValueError:应为类型为('\n\t\t{\n\t\t“deviceid:'、108749'、\n\t\t“fromnumber:'、'+1-000-000-0001'、'、\n\t\t“body:'、'[21:01]EmojiGuy#7257:spoopy机器人已死亡或它已进行检查,然后我猜','\n\t\t\t}\n\t')
有人能解释一下那是什么吗?我试过一些方法,比如用
替换
+hg_-api
,hg_-api
等等,但都没用

我不明白怎么了。我在谷歌上搜索了错误信息和所有信息,似乎找不到解决办法


(使用Discord Python API和hologram.io API)

是一个元组,而不是单个字符串:

values = """
  {
    "deviceid": """,hg_deviceid,""",
    "fromnumber": """,sender,""",
    "body": """,body,"""
  }
"""
这是一系列字符串,用逗号分隔

使用
JSON
库为您编码字典,而不是手动构建JSON字符串。加

import json
导入并使用它生成

values = json.dumps({
    "deviceid": hg_deviceid,
    "fromnumber": sender,
    "body": body,
}).encode('utf8')

是一个元组。看看定义中所有的逗号。听起来您可能对字符串插值的方法感兴趣。(再看一遍,
可能应该使用
json.dumps
构造,但是
str.format
对于许多其他字符串操作都很有用。)
namererror:name'json'未定义
@Coto:您确实需要导入库:
import json
TypeError:POST数据应为字节或字节数。它不能是str类型。