将python2代码转换为python3问题



所以我一直在尝试转换一个用python2编写的omegle bot到python3。这是原始代码:https://gist.github.com/thefinn93/1543082

现在这是我的代码:

import requests
import sys
import json
import urllib
import random
import time
server = b"odo-bucket.omegle.com"
debug_log = False   # Set to FALSE to disable excessive messages
config = {'verbose': open("/dev/null","w")}
headers = {}
headers['Referer'] = b'http://odo-bucket.omegle.com/'
headers['Connection'] = b'keep-alive'
headers['User-Agent'] = b'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.2 (KHTML, like Gecko) Ubuntu/11.10 Chromium/15.0.874.106 Chrome/15.0.874.106 Safari/535.2'
headers['Content-type'] = b'application/x-www-form-urlencoded; charset=UTF-8'
headers['Accept'] = b'application/json'
headers['Accept-Encoding'] = b'gzip,deflate,sdch'
headers['Accept-Language'] = b'en-US'
headers['Accept-Charset'] = b'ISO-8859-1,utf-8;q=0.7,*;q=0.3'
if debug_log:
    config['verbose'] = debug_log
def debug(msg):
    if debug_log:
        print("DEBUG: " + str(msg))
        debug_log.write(str(msg) + "n")
def getcookies():
    r = requests.get(b"http://" + server + b"/")
    debug(r.cookies)
    return(r.cookies)
def start():
    r = requests.request(b"POST", b"http://" + server + b"/start?rcs=1&spid=", data=b"rcs=1&spid=", headers=headers)
    omegle_id = r.content.strip(b""")
    print("Got ID: " + str(omegle_id))
    cookies = getcookies()
    event(omegle_id, cookies)
def send(omegle_id, cookies, msg):
    r = requests.request(b"POST","http://" + server + "/send", data="msg=" + urllib.quote_plus(msg) + "&id=" + omegle_id, headers=headers, cookies=cookies)
    if r.content == "win":
        print("You: " + msg)
    else:
        print("Error sending message, check the log")
        debug(r.content)
def event(omegle_id, cookies):
    captcha = False
    next = False
    r = requests.request(b"POST",b"http://" + server + b"/events",data=b"id=" + omegle_id, cookies=cookies, headers=headers)
    try:
        parsed = json.loads(r.content)
        for e in parsed:
            if e[0] == "waiting":
                print("Waiting for a connection...")
            elif e[0] == "count":
                print("There are " + str(e[1]) + " people connected to Omegle")
            elif e[0] == "connected":
                print("Connection established!")
                send(omegle_id, cookies, "HI I just want to talk ;_;")
            elif e[0] == "typing":
                print("Stranger is typing...")
            elif e[0] == "stoppedTyping":
                print ("Stranger stopped typing")
            elif e[0] == "gotMessage":
                print("Stranger: " + e[1])
                try:
                    cat=""
                    time.sleep(random.randint(1,5))
                    i_r=random.randint(1,8)
                    if i_r==1:
                        cat="that's cute :3"
                    elif i_r==2:
                        cat="yeah, guess your right.."
                    elif i_r==3:
                        cat="yeah, tell me something about yourself!!"
                    elif i_r==4:
                        cat="what's up"
                    elif i_r==5:
                        cat="me too"
                    else:
                        time.sleep(random.randint(3,9))
                        send(omegle_id, cookies, "I really have to tell you something...")
                    time.sleep(random.randint(3,9))
                    cat="I love you."
                    send(omegle_id, cookies, cat)
                except:
                    debug("Send errors!")
            elif e[0] == "strangerDisconnected":
                print("Stranger Disconnected")
                next = True
            elif e[0] == "suggestSpyee":
                print ("Omegle thinks you should be a spy. Fuck omegle.")
            elif e[0] == "recaptchaRequired":
                print("Omegle think's you're a bot (now where would it get a silly idea like that?). Fuckin omegle. Recaptcha code: " + e[1])
                captcha = True
    except:
        print("Derka derka derka")
    if next:
        print("Reconnecting...")
        start()
    elif not captcha:
        event(omegle_id, cookies)
start()
我得到的错误是:
Traceback (most recent call last):
  File "p3.py", line 124, in <module>
    start()
  File "p3.py", line 46, in start
    r = requests.request(b"POST", b"http://" + server + b"/start?rcs=1&spid=", data=b"rcs=1&spid=", headers=headers)
  File "/usr/lib/python3.4/site-packages/requests/api.py", line 44, in request
    return session.request(method=method, url=url, **kwargs)
  File "/usr/lib/python3.4/site-packages/requests/sessions.py", line 456, in request
    resp = self.send(prep, **send_kwargs)
  File "/usr/lib/python3.4/site-packages/requests/sessions.py", line 553, in send
    adapter = self.get_adapter(url=request.url)
  File "/usr/lib/python3.4/site-packages/requests/sessions.py", line 608, in get_adapter
    raise InvalidSchema("No connection adapters were found for '%s'" % url)
requests.exceptions.InvalidSchema: No connection adapters were found for 'b'http://odo-bucket.omegle.com/start?rcs=1&spid=''

我真的不明白如何解决这个错误,也不知道问题到底是什么,即使在查找之后。

更新:现在,在删除所有的b之后,我得到以下错误:

Traceback (most recent call last):
  File "p3.py", line 124, in <module>
    start()
  File "p3.py", line 47, in start
    omegle_id = r.content.strip(""")
TypeError: Type str doesn't support the buffer API

更新2:将b放回r.p content后,我得到以下错误消息:

Traceback (most recent call last):
  File "p3.py", line 124, in <module>
    start()
  File "p3.py", line 50, in start
    event(omegle_id, cookies)
  File "p3.py", line 63, in event
    r = requests.request("POST","http://" + server + "/events",data="id=" + omegle_id,   cookies=cookies, headers=headers)
TypeError: Can't convert 'bytes' object to str implicitly

更新3:每次我尝试启动它时,除了"Derka Derka",可能会导致这种情况(它不像python2)。

requests接受字符串,而不是URL的bytes值。

因为你的url是bytes值,requestsstr()将它们转换为字符串,结果字符串在开始时包含字符b'。这不是像http://https://那样有效的方案。

字节串的多数应该是常规字符串;只有content.strip()调用处理实际字节。

例如,

头将为您编码。甚至不要设置Content-Type头;如果您将字典(使用字符串键和值)传递给data关键字参数,requests将为您处理此问题。

你也不应该设置Connection头;将连接管理留给requests

最新更新