What’s wrong with Twitter messaging?

Asked

Viewed 160 times

1

import urllib.request
import time

def send_to_twitter(msg):
    password_manager = urllib.request.HTTPPasswordMgr()
    password_manager.add_password("Twitter API","http://twitter.com/statuses","usuário","senha")
    http_handler = urllib.request.HTTPBasicAuthHandler(password_manager)
    page_opener = urllib.request.build_opener(http_handler)
    urllib.request.install_opener(page_opener)
    params = urllib.parse.urlencode( {'status':msg} )
    resp = urllib.request.urlopen("http://twitter.com/statuses/update.json",params)
    resp.read()

def get_price():
    page = urllib.request.urlopen("http://beans-r-us.appspot.com/prices-loyalty.html")
    text = page.read().decode("utf8")
    where = text.find('>$')
    start_of_price = where + 2
    end_of_price = start_of_price + 4
    return(text[start_of_price : end_of_price])

escolha = input("Precisa do valor imediatamente? ")

if escolha == 'y':
    send_to_twitter(get_price())
else:
    if escolha == 'n':
        price = 99.99
        while price > 4.74:
            price = float(get_price())
            time.sleep(3)
        send_to_twitter('BUY!')
    else:
        print("Voce nao escolheu nada")

Error message:

Traceback (most recent call last):
  File "(livro)programa_com_escolha_cafe.py", line 25, in <module>
    send_to_twitter(get_price())
  File "(livro)programa_com_escolha_cafe.py", line 11, in send_to_twitter
    resp = urllib.request.urlopen("http://twitter.com/statuses/update.json",params)
  File "/usr/lib/python3.5/urllib/request.py", line 163, in urlopen
    return opener.open(url, data, timeout)
  File "/usr/lib/python3.5/urllib/request.py", line 464, in open
    req = meth(req)
  File "/usr/lib/python3.5/urllib/request.py", line 1183, in do_request_
    raise TypeError(msg)
TypeError: POST data should be bytes or an iterable of bytes. It cannot be of type str.

1 answer

1

You have to send the POST data in bytes:

...
params = urllib.parse.urlencode( {'status':msg} ).encode("utf-8")
...

.encode("utf-8")serves to make the Encode of a string 'utf-8' for bytes

More information here

  • So I fixed the code by putting what you said but more error messages appeared, I saw in other places that the problem may be the twitter API that "changed" (because this code is from a book to teach programming that has already a time), you would not know how to orient me with the "new" twitter API?

  • @Gabrielsantos but the problem he posed in the question is solved. As for others I have no idea, No ca worked with this apj

Browser other questions tagged

You are not signed in. Login or sign up in order to post.