Tweepy回复提及机器人

时间:2020-01-29 23:45:23

标签: python tweepy

当我运行该脚本以回复Tweepy的Twitter提及时,我不断收到错误NameError:未定义名称'create_api',我不确定为什么。我在这里想念什么?任何帮助将不胜感激。谢谢

import tweepy
import logging
import time

def create_api():
    consumer_key = 'xxxxx'
    consumer_secret = 'xxxxx'
    access_token = 'xxxx-xxxx'
    access_token_secret = 'xxxx'

auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
api = tweepy.API(auth, wait_on_rate_limit=True, 
wait_on_rate_limit_notify=True)
try:
    api.verify_credentials()
    except Exception as e:
        logger.error("Error creating API", exc_info=True)
        raise e
    logger.info("API created")
    return api

def check_mentions(api, keywords, since_id):
    logger.info("Retrieving mentions")
    new_since_id = since_id
    for tweet in tweepy.Cursor(api.mentions_timeline,
        since_id=since_id).items():
        new_since_id = max(tweet.id, new_since_id)
        if tweet.in_reply_to_status_id is not None:
            continue
        if any(keyword in tweet.text.lower() for keyword in keywords):
            logger.info(f"Answering to {tweet.user.name}")

            if not tweet.user.following:
                tweet.user.follow()

            api.update_status(
                status="Please reach us via DM",
                in_reply_to_status_id=tweet.id,
            )
    return new_since_id

def main():
    api = create_api()
    since_id = 1
    while True:
        since_id = check_mentions(api, ["help", "support"], since_id)
        logger.info("Waiting...")
        time.sleep(60)

if __name__ == "__main__":
    main()

2 个答案:

答案 0 :(得分:0)

看来您的大多数错误都来自缩进不当。这是我修复缩进问题的代码版本。

我得到NameError: name 'logger' is not defined是因为使用logging库的正确方法是使用logging.x而不是logger。这似乎是一个小错字。

解决此问题后,我得到tweepy.error.TweepError: [{'code': 89, 'message': 'Invalid or expired token.'}],这是可以预期的,因为我没有有效的令牌。

import tweepy
import logging
import time

def create_api():
    consumer_key = 'xxxxx'
    consumer_secret = 'xxxxx'
    access_token = 'xxxx-xxxx'
    access_token_secret = 'xxxx'

    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    api = tweepy.API(auth, wait_on_rate_limit=True, 
    wait_on_rate_limit_notify=True)
    try:
        api.verify_credentials()
    except Exception as e:
        logging.error("Error creating API", exc_info=True)
        raise e
    logging.info("API created")
    return api

def check_mentions(api, keywords, since_id):
    logging.info("Retrieving mentions")
    new_since_id = since_id
    for tweet in tweepy.Cursor(api.mentions_timeline,
        since_id=since_id).items():
        new_since_id = max(tweet.id, new_since_id)
        if tweet.in_reply_to_status_id is not None:
            continue
        if any(keyword in tweet.text.lower() for keyword in keywords):
            logging.info(f"Answering to {tweet.user.name}")

            if not tweet.user.following:
                tweet.user.follow()

            api.update_status(
                status="Please reach us via DM",
                in_reply_to_status_id=tweet.id,
            )
    return new_since_id

def main():
    api = create_api()
    since_id = 1
    while True:
        since_id = check_mentions(api, ["help", "support"], since_id)
        logging.info("Waiting...")
        time.sleep(60)

if __name__ == "__main__":
    main()

输出:(以显示日志记录正在捕获错误)

ERROR:root:Error creating API
Traceback (most recent call last):
  File ".\stack15.py", line 16, in create_api
    api.verify_credentials()
  File "C:\Users\xxxxxxx\source\repos\PyProjects\py_3.7\lib\site-packages\tweepy\api.py", line 605, in verify_credentials
    )(**kargs)
  File "C:\Users\xxxxxxx\source\repos\PyProjects\py_3.7\lib\site-packages\tweepy\binder.py", line 250, in _call
    return method.execute()
  File "C:\Users\xxxxxxx\source\repos\PyProjects\py_3.7\lib\site-packages\tweepy\binder.py", line 233, in execute
    raise TweepError(error_msg, resp, api_code=api_error_code)
tweepy.error.TweepError: [{'code': 89, 'message': 'Invalid or expired token.'}]
Traceback (most recent call last):
  File ".\stack15.py", line 52, in <module>
    main()
  File ".\stack15.py", line 44, in main
    api = create_api()
  File ".\stack15.py", line 19, in create_api
    raise e
  File ".\stack15.py", line 16, in create_api
    api.verify_credentials()
  File "C:\Users\xxxxxxx\source\repos\PyProjects\py_3.7\lib\site-packages\tweepy\api.py", line 605, in verify_credentials
    )(**kargs)
  File "C:\Users\xxxxxxx\source\repos\PyProjects\py_3.7\lib\site-packages\tweepy\binder.py", line 250, in _call
    return method.execute()
  File "C:\Users\xxxxxxx\source\repos\PyProjects\py_3.7\lib\site-packages\tweepy\binder.py", line 233, in execute
    raise TweepError(error_msg, resp, api_code=api_error_code)
tweepy.error.TweepError: [{'code': 89, 'message': 'Invalid or expired token.'}]

答案 1 :(得分:0)

回复时,使用 tweet.id_str 而不是 tweet.id