2

私は twitch irc ボットに取り組んでおり、利用可能にしたいコンポーネントの 1 つは、ボットが閉じるときに引用符をペーストビン ペーストに保存し、起動時に同じ引用符を取得する機能でした。

私は保存部分から始めましたが、有効な投稿を取得できないように見える障害にぶつかり、方法がわかりません。

#!/usr/bin/env python3

import urllib.parse
import urllib.request

# --------------------------------------------- Pastebin Requisites --------------------------------------------------

pastebin_key = 'my pastebin key'  # developer api key, required. GET: http://pastebin.com/api
pastebin_password = 'password'  # password for pastebin_username
pastebin_postexp = 'N'  # N = never expire
pastebin_private = 0  # 0 = Public 1 = unlisted 2 = Private
pastebin_url = 'http://pastebin.com/api/api_post.php'
pastebin_username = 'username'  # user corresponding with key


# --------------------------------------------- Value clean up --------------------------------------------------

pastebin_password = urllib.parse.quote(pastebin_password, safe='/')
pastebin_username = urllib.parse.quote(pastebin_username, safe='/')

# --------------------------------------------- Pastebin Functions --------------------------------------------------

def post(title, content):  # used for posting a new paste
    pastebin_vars = {'api_option': 'paste', 'api_user_key':     pastebin_username, 'api_paste_private': pastebin_private,
                 'api_paste_name': title, 'api_paste_expire_date': pastebin_postexp,  'api_dev_key': pastebin_key,
                 'api_user_password': pastebin_password, 'api_paste_code': content}
    try:
        str_to_paste = ', '.join("{!s}={!r}".format(key, val) for (key, val) in pastebin_vars.items())  # dict to str :D
        str_to_paste = str_to_paste.replace(":", "")  # remove :
        str_to_paste = str_to_paste.replace("'", "")  # remove '
        str_to_paste = str_to_paste.replace(")", "")  # remove )
        str_to_paste = str_to_paste.replace(", ", "&")  # replace dividers with &
        urllib.request.urlopen(pastebin_url, urllib.parse.urlencode(pastebin_vars)).read()
        print('did that work?')
    except:
        print("post submit failed :(")
        print(pastebin_url + "?" + str_to_paste)  # print the output for test

 post("test", "stuff")

私はより多くのライブラリやものをインポートすることにオープンですが、これに2日間続けて取り組んだ後、何が間違っているのかよくわかりません:S

4

4 に答える 4

0

ペーストビンは今まで知りませんでした。私は彼らのAPIを読んで初めて試してみましたが、完全にうまくいきました.

これが私がしたことです:

  • を取得するためにログインしましたapi_user_key
  • と一緒に投稿にそれを含めましたapi_dev_key
  • ウェブサイトを確認したところ、投稿がありました。

コードは次のとおりです。

import urllib.parse
import urllib.request


def post(url, params):
    data = urllib.parse.urlencode(login_params).encode("utf-8")
    req = urllib.request.Request(login_url, data)
    with urllib.request.urlopen(req) as response:
       return response.read()


# Logging in to fetch api_user_key
login_url = "http://pastebin.com/api/api_login.php"
login_params = {"api_dev_key": "<the dev key they gave you",
                "api_user_name": "<username goes here>",
                "api_user_password": "<password goes here>"}
api_user_key = post(login_url, login_params)


# Posting some random text
post_url = "http://pastebin.com/api/api_post.php"
post_params = {"api_dev_key": "<the dev key they gave you",
               "api_option": "paste",
               "api_paste_code": "<head>Testing</head>",
               "api_paste_private": "0",
               "api_paste_name": "testing.html",
               "api_paste_expire_date": "10M",
               "api_paste_format": "html5",
               "api_user_key": api_user_key}
response = post(post_url, post_params)

何かを投稿するために必要なのは最初の 3 つのパラメーターのみで、残りはオプションです。

于 2015-08-03T00:56:42.453 に答える
0

まず、あなたのtry/exceptブロックは実際のエラーを捨てています。except元の例外をキャプチャまたは再発生させることなく、「裸の」句を使用することはほとんどありません。完全な説明については、この記事を参照してください。

try/を削除するexceptと、根本的なエラーが表示されます。

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "paste.py", line 42, in post
    urllib.request.urlopen(pastebin_url, urllib.parse.urlencode(pastebin_vars)).read()
  File "/usr/lib/python3.4/urllib/request.py", line 161, in urlopen
    return opener.open(url, data, timeout)
  File "/usr/lib/python3.4/urllib/request.py", line 461, in open
    req = meth(req)
  File "/usr/lib/python3.4/urllib/request.py", line 1112, in do_request_
    raise TypeError(msg)
TypeError: POST data should be bytes or an iterable of bytes. It cannot be of type str.

これは、バイトを期待する関数に Unicode 文字列を渡そうとしていることを意味します。I/O (ディスク上のファイルの読み取り/書き込み、HTTP 経由でのデータの送受信など) を行うときは、通常、Unicode 文字列をバイトとしてエンコードする必要があります。Unicode とバイトの適切な説明と、エンコードとデコードが必要な場合については、このプレゼンテーションを参照してください。

次に、この行:

urllib.request.urlopen(pastebin_url, urllib.parse.urlencode(pastebin_vars)).read()

応答を破棄しているため、API 呼び出しの結果を知る方法がありません。これを変数に割り当てるか、関数から返すと、値を調べることができます。貼り付ける URL か、API からのエラー メッセージのいずれかになります。

次に、あなたのコードは多くの不要なパラメーターを API に送信しており、str_to_pasteステートメントは不要だと思います。

次のはるかに単純なコードを使用して、貼り付けを行うことができました。

import urllib.parse
import urllib.request

PASTEBIN_KEY = 'my-api-key' # developer api key, required. GET: http://pastebin.com/api
PASTEBIN_URL = 'http://pastebin.com/api/api_post.php'

def post(title, content):  # used for posting a new paste
    pastebin_vars = dict(
        api_option='paste',
        api_dev_key=PASTEBIN_KEY,
        api_paste_name=title,
        api_paste_code=content,
    )
    return urllib.request.urlopen(PASTEBIN_URL, urllib.parse.urlencode(pastebin_vars).encode('utf8')).read()

ここでそれが使用されています:

>>> post("test", "hello\nworld.")
b'http://pastebin.com/v8jCkHDB'
于 2015-08-03T00:58:20.760 に答える