close

最近跟朋友討論到PTT的登入天數,才發現自以為使用PTT很久的我,登入天數居然連四位數都沒有,這問題出在雖然我常常看PTT,但只要一忙就可能整天不開PTT,也就導致少掉一天的紀錄,所以突發奇想的我就決定來做一個每天自動登入PTT的小程式。

原本想找找看PTT有沒有提供API供人使用,但很可惜沒有那種東西,所以要回到最原始的方式,就是telnet連進去做登入的動作,因為最近開始在摸Python,所以這次的小程式是使用python 3.6來做的,在開始之前除了要安裝python3.6之外,還要安裝一個叫做APScheduler的model。

這是使用telnetlib模組telnet進ptt.cc的部分比較需要注意的是文字編碼的問題,都是encode('big5')。

TELNET連進ptt.cc程式碼:

import telnetlib
import sys
import time


host = 'ptt.cc'
user = 'user'
password = 'passwd'


telnet = telnetlib.Telnet(host)
time.sleep(1)
content = telnet.read_very_eager().decode('big5','ignore')
print(content)

if u"請輸入代號" in content:
	print("輸入帳號中...")
	telnet.write((user + "\r\n").encode('big5'))
	time.sleep(1)
	
	content = telnet.read_very_eager().decode('big5','ignore')
	
	print(content)
	
	if u"請輸入您的密碼" in content:
		print("輸入密碼中...")
		telnet.write((password + "\r\n").encode('big5') )
		time.sleep(1)
		
		content = telnet.read_very_eager().decode('big5','ignore')
		
		print(content)
		
		if u"您想刪除其他重複登入的連線嗎" in content:
			print("不刪除其他登入...")
			telnet.write(("n\r\n").encode('big5'))
			time.sleep(1)
			content = telnet.read_very_eager().decode('big5','ignore')
			print(content)
		
			if u"請按任意鍵繼續" in content:
				print("資訊頁面,按任意鍵繼續...")
				telnet.write(("\r\n").encode('big5') )
				time.sleep(2)
				content = telnet.read_very_eager().decode('big5','ignore')
				print(content)

定時重複執行程式碼:

from apscheduler.schedulers.blocking import BlockingScheduler
from datetime import datetime
import os

def job():
	os.system("python3 telnetPTT.py")

scheduler=BlockingScheduler()
scheduler.add_job(job, 'cron', day_of_week='1-6',hour=00,minute=1)
scheduler.start()

函式job的內容為執行連結登入ptt的程式。

第9行:第一個參數為要執行的函式名稱,day_of_week為一周執行的天數,hour以及minute每日執行的時間。

 


我把這支程式掛在我的RaspberryPi上面,讓它24小時執行,你也可以直接在windows中執行,或是使用上面提到的技巧,做些對社會更有幫助的小程式跟我分享喔。

好了,以上是小弟個人的關於解PTT每日登入成就的小程式,給大家參考,如有誤人子弟之處,還請各位先進給予指教。

如果覺得本篇文章對你有幫助的話,也請別忘記留言給予鼓勵喔。

arrow
arrow
    文章標籤
    PYTHON PTT 自動登入
    全站熱搜

    zhong.jun.jimmy 發表在 痞客邦 留言(2) 人氣()