Last active
March 16, 2023 00:44
-
-
Save fredchu/05ed598a499396cfbb2780276b5fefb2 to your computer and use it in GitHub Desktop.
Twitter bot sample
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import tweepy | |
import schedule | |
import time | |
# 填入你的 API Key 和 API Secret | |
api_key = 'YOUR_API_KEY_HERE' | |
api_secret = 'YOUR_API_SECRET_HERE' | |
# 填入你的 Access Token 和 Access Token Secret | |
access_token = 'YOUR_ACCESS_TOKEN_HERE' | |
access_secret = 'YOUR_ACCESS_SECRET_HERE' | |
# 設定 tweepy 套件 | |
auth = tweepy.OAuth1UserHandler( | |
api_key, api_secret, access_token, access_secret) | |
api = tweepy.API(auth) | |
# 定義發推文的函數 | |
def send_tweet(message): | |
api.update_status(message) | |
# 發送早上九點二分的推文 | |
def send_morning_tweet(): | |
message = '大家好👋 早安!' | |
send_tweet(message) | |
# 發送下午十二點三分的推文 | |
def send_afternoon_tweet(): | |
message = '大家好👋 午安!' | |
send_tweet(message) | |
# 定時發送推文 | |
schedule.every().day.at('09:02').do(send_morning_tweet) | |
schedule.every().day.at('12:03').do(send_afternoon_tweet) | |
# 監聽 mention 事件 | |
class MyStreamListener(tweepy.StreamListener): | |
def on_status(self, status): | |
if status.in_reply_to_status_id is not None or status.user.id == api.me().id: | |
# 過濾掉回覆和自己發的 tweet | |
return | |
elif any(keyword in status.text.lower() for keyword in ['@YOUR_BOT_USERNAME']): | |
# 如果有提到機器人的 username | |
on_mention(status) | |
my_stream_listener = MyStreamListener() | |
my_stream = tweepy.Stream(auth = api.auth, listener=my_stream_listener) | |
my_stream.filter(track=['@YOUR_BOT_USERNAME'], is_async=True) | |
while True: | |
schedule.run_pending() | |
time.sleep(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment