Tweepy 回复提及机器人

当我运行此脚本以使用 Tweepy 回复 Twitter 提及时,我不断收到错误 NameError: name 'create_api' is not defined 我不知道为什么。我在这里想念什么?任何帮助将不胜感激。谢谢


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()



暮色呼如
浏览 203回答 2
2回答

繁华开满天机

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

胡说叔叔

似乎您的大多数错误都来自不正确的缩进。这是我修复缩进问题的代码版本。我明白了,因为使用库NameError: name 'logger' is not defined的正确方法是使用而不是. 这似乎是一个小错字。logginglogging.xlogger修复该问题后,我得到了tweepy.error.TweepError: [{'code': 89, 'message': 'Invalid or expired token.'}],这是意料之中的,因为我没有有效的令牌。import tweepyimport loggingimport timedef create_api():&nbsp; &nbsp; consumer_key = 'xxxxx'&nbsp; &nbsp; consumer_secret = 'xxxxx'&nbsp; &nbsp; access_token = 'xxxx-xxxx'&nbsp; &nbsp; access_token_secret = 'xxxx'&nbsp; &nbsp; auth = tweepy.OAuthHandler(consumer_key, consumer_secret)&nbsp; &nbsp; auth.set_access_token(access_token, access_token_secret)&nbsp; &nbsp; api = tweepy.API(auth, wait_on_rate_limit=True,&nbsp;&nbsp; &nbsp; wait_on_rate_limit_notify=True)&nbsp; &nbsp; try:&nbsp; &nbsp; &nbsp; &nbsp; api.verify_credentials()&nbsp; &nbsp; except Exception as e:&nbsp; &nbsp; &nbsp; &nbsp; logging.error("Error creating API", exc_info=True)&nbsp; &nbsp; &nbsp; &nbsp; raise e&nbsp; &nbsp; logging.info("API created")&nbsp; &nbsp; return apidef check_mentions(api, keywords, since_id):&nbsp; &nbsp; logging.info("Retrieving mentions")&nbsp; &nbsp; new_since_id = since_id&nbsp; &nbsp; for tweet in tweepy.Cursor(api.mentions_timeline,&nbsp; &nbsp; &nbsp; &nbsp; since_id=since_id).items():&nbsp; &nbsp; &nbsp; &nbsp; new_since_id = max(tweet.id, new_since_id)&nbsp; &nbsp; &nbsp; &nbsp; if tweet.in_reply_to_status_id is not None:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; continue&nbsp; &nbsp; &nbsp; &nbsp; if any(keyword in tweet.text.lower() for keyword in keywords):&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; logging.info(f"Answering to {tweet.user.name}")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if not tweet.user.following:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; tweet.user.follow()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; api.update_status(&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; status="Please reach us via DM",&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; in_reply_to_status_id=tweet.id,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; )&nbsp; &nbsp; return new_since_iddef main():&nbsp; &nbsp; api = create_api()&nbsp; &nbsp; since_id = 1&nbsp; &nbsp; while True:&nbsp; &nbsp; &nbsp; &nbsp; since_id = check_mentions(api, ["help", "support"], since_id)&nbsp; &nbsp; &nbsp; &nbsp; logging.info("Waiting...")&nbsp; &nbsp; &nbsp; &nbsp; time.sleep(60)if __name__ == "__main__":&nbsp; &nbsp; main()输出:(显示日志记录正在捕获错误)ERROR:root:Error creating APITraceback (most recent call last):&nbsp; File ".\stack15.py", line 16, in create_api&nbsp; &nbsp; api.verify_credentials()&nbsp; File "C:\Users\xxxxxxx\source\repos\PyProjects\py_3.7\lib\site-packages\tweepy\api.py", line 605, in verify_credentials&nbsp; &nbsp; )(**kargs)&nbsp; File "C:\Users\xxxxxxx\source\repos\PyProjects\py_3.7\lib\site-packages\tweepy\binder.py", line 250, in _call&nbsp; &nbsp; return method.execute()&nbsp; File "C:\Users\xxxxxxx\source\repos\PyProjects\py_3.7\lib\site-packages\tweepy\binder.py", line 233, in execute&nbsp; &nbsp; 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):&nbsp; File ".\stack15.py", line 52, in <module>&nbsp; &nbsp; main()&nbsp; File ".\stack15.py", line 44, in main&nbsp; &nbsp; api = create_api()&nbsp; File ".\stack15.py", line 19, in create_api&nbsp; &nbsp; raise e&nbsp; File ".\stack15.py", line 16, in create_api&nbsp; &nbsp; api.verify_credentials()&nbsp; File "C:\Users\xxxxxxx\source\repos\PyProjects\py_3.7\lib\site-packages\tweepy\api.py", line 605, in verify_credentials&nbsp; &nbsp; )(**kargs)&nbsp; File "C:\Users\xxxxxxx\source\repos\PyProjects\py_3.7\lib\site-packages\tweepy\binder.py", line 250, in _call&nbsp; &nbsp; return method.execute()&nbsp; File "C:\Users\xxxxxxx\source\repos\PyProjects\py_3.7\lib\site-packages\tweepy\binder.py", line 233, in execute&nbsp; &nbsp; raise TweepError(error_msg, resp, api_code=api_error_code)tweepy.error.TweepError: [{'code': 89, 'message': 'Invalid or expired token.'}]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python