- สิ่งแรกที่ทำต้องผูกเบอร์เข้ากับ twitter setting ปกติของเราก่อนถึงจะสร้าง application ได้
- เข้า https://apps.twitter.com/ และ Create New App ขึ้นมา และกรอกเฉพาะข้อมูลที่จำเป็น
- ใน Application settings ตรง Access level ให้เลือกเป็น Read and write เพื่อให้เรา send tweet ได้
- แถบ Key and Access Token ให้กดปุ่ม generate ขึ้นมา
โดยของที่จำเป็นทั้งหมดที่ต้องใช้มี 4 ตัวคือ consumer key, consumer secret, access token
และ access token secret
Access API
วิธีง่ายมากกกก เราใช้ tweepy ในการ access API ของ twitter และอย่าลืม
pip install tweepy
สร้างไฟล์ auto_tweet.py
from datetime import datetime
from pytz import timezone
import tweepy
class TwitterAPI:
def __init__(self):
consumer_key = "XXXX"
consumer_secret = "XXXXX"
access_token = "XXXXX"
access_token_secret = "XXXXX"
auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
auth.set_access_token(access_token, access_token_secret)
self.api = tweepy.API(auth)
def tweet(self, message):
self.api.update_status(status=message)
if __name__ == "__main__":
fmt = "%Y-%m-%d %H:%M:%S %Z%z"
now_utc = datetime.now(timezone('UTC')) # Current time in UTC
now_bkk = now_utc.astimezone(timezone('Asia/Bangkok')) #converting an existing localized time using the standard astimezone() method
message = now_bkk.strftime(fmt) #turn into string
twit = TwitterAPI()
twit.tweet("Current time is " + message)
แต่เดี๋ยวก่อน อย่าลืมลง library pytz ด้วย ก่อนรันไฟล์ด้วยนะ
pip install pytz
(http://pytz.sourceforge.net/)
เรา post tweet ด้วย
api.update_status(status=message)
(http://docs.tweepy.org/en/latest/api.html)
Setting Cron
เพราะเราไม่อยากที่จะต้องมา python auto_tweet.py ทุกครั้ง Cron จึงเป็นตัวเลือกที่หลายๆคนหยิบมาใช้
สมมติเราอยากให้ automate ทวีตบอกเวลาตอน เที่ยง, บ่ายโมง และ สี่ทุ่ม
crontab -e
0 12,13,22 * * * /vagrant/auto_tweet/venv/bin/python /vagrant/auto_tweet/auto_tweet.py
ถ้าไม่รู้ว่าเขียนยังไง เชิญนี้เลยย
ผลที่ได้
note. กรณีต้องแก้ timezone บน Ubuntu เพราะรัน cron ที่ exact time ไม่ได้ อย่างตัวอย่างด้านบน(12.00, 13.00, ..) เพราะเวลาของ vagrant ยังไม่ตรงกับ current time ดังนั้นจึงต้องแก้ timezone ให้เรียบร้อยก่อน ตามด้วย restart cron ใหม่
sudo service cron restart
หรือหากอยากดูว่า cron ทำตามที่สั่งไหม เข้าไป
sudo vi /etc/rsyslog.d/50-default.conf
เอา uncomment บรรทัดนี้ออก
#cron.* /var/log/cron.log
restart rsyslog และ cron
sudo service rsyslog restart
sudo service cron restart
คราวนี้ก็ดูที่ /var/log/cron.log ว่า cronjob ได้ถูก run หรือไม่
ref.
https://blog.twitter.com/2014/getting-started-with-automation-on-twitter
http://nodotcom.org/python-twitter-tutorial.html
http://www.dototot.com/how-to-write-a-twitter-bot-with-python-and-tweepy/
Leave a comment