def Loginout(): print('WebSocket 登入登出測試') PTTBot = PTT.Library(ConnectMode=PTT.ConnectMode.WebSocket, LogLevel=PTT.LogLevel.DEBUG) try: PTTBot.login( ID, Password, # KickOtherLogin=True ) except PTT.Exceptions.LoginError: PTTBot.log('登入失敗') sys.exit() PTTBot.log('登入成功') PTTBot.logout() PTTBot.log('登出成功') print('等待五秒') time.sleep(5) return print('Telnet 登入登出測試') PTTBot = PTT.Library(ConnectMode=PTT.ConnectMode.Telnet, # LogLevel=PTT.LogLevel.DEBUG ) try: PTTBot.login(ID, Password, KickOtherLogin=True) except PTT.Exceptions.LoginError: PTTBot.log('登入失敗') sys.exit() PTTBot.log('登入成功') PTTBot.logout() PTTBot.log('登出成功')
def PerformanceTest(): TestTime = 1000 print(f'效能測試 getTime {TestTime} 次') PTTBot = PTT.Library( ConnectMode=PTT.ConnectMode.WebSocket, LogLevel=PTT.LogLevel.SLIENT, # LogLevel=PTT.LogLevel.DEBUG, ) try: PTTBot.login(ID, Password, KickOtherLogin=True) except PTT.Exceptions.LoginError: PTTBot.log('登入失敗') sys.exit() PTTBot.log('登入成功') StartTime = time.time() for _ in range(TestTime): PTT_TIME = PTTBot.getTime() if PTT_TIME is None: print('PTT_TIME is None') break # print(PTT_TIME) EndTime = time.time() PTTBot.logout() PTTBot.log('Performance Test WebSocket ' + str(round(EndTime - StartTime, 2)) + ' s') PTTBot.log('等待五秒') time.sleep(5) PTTBot = PTT.Library( ConnectMode=PTT.ConnectMode.Telnet, LogLevel=PTT.LogLevel.SLIENT, # LogLevel=PTT.LogLevel.DEBUG, ) try: PTTBot.login(ID, Password, KickOtherLogin=True) except PTT.Exceptions.LoginError: PTTBot.log('登入失敗') sys.exit() PTTBot.log('登入成功') StartTime = time.time() for _ in range(TestTime): PTT_TIME = PTTBot.getTime() if PTT_TIME is None: print('PTT_TIME is None') break # print(PTT_TIME) EndTime = time.time() PTTBot.log('Performance Test Telnet ' + str(round(EndTime - StartTime, 2)) + ' s') print('Performance Test finish')
def PTTlogin(self): self.PTTBot = PTT.Library(self.ID, self.Password, kickOtherLogin=False, _LogLevel=PTT.LogLevel.DEBUG) ErrCode = self.PTTBot.login() self.Tempo()
def GetPttData(): print('Input your ID') ID = input() print('Input your password') Password = input() PTTBot = PTT.Library() ErrCode = PTTBot.login(ID, Password) if ErrCode != PTT.ErrorCode.Success: PTTBot.Log('登入失敗') sys.exit() # return a datatype with various information # getPost( board, article index) ErrCode, Post = PTTBot.getPost('Gossiping', PostIndex=44444) title = Post.getTitle() content = Post.getContent() author = Post.getAuthor() #PTTBot.Log('標題: ' + Post.getTitle()) #PTTBot.Log('內文:\n' + Post.getContent()) #PTTBot.Log('作者: ' + Post.getAuthor()) print(title) print(content) print(author) return Post PTTBot.logout()
def LoginLogout(): # 登入登出範例 # Library 參數 # LogLevel (Optional): # PTT.LogLevel.DEBUG # PTT.LogLevel.INFO (預設值) # PTT.LogLevel.SLIENT # Language (Optional): # PTT.Language.Chinese (預設值) # PTT.Language.English # login() 參數 # ID: # 你的 PTT 帳號 # Password: # 你的 PTT 密碼 # KickOtherLogin (Optional): # 是否剔除其他登入。 # 預設值為 False # logout() 無參數輸入 PTTBot = PTT.Library() try: PTTBot.login(ID, Password) except PTT.Exceptions.LoginError: PTTBot.log('登入失敗') return PTTBot.log('登入成功') PTTBot.logout()
def __init__(self): f = open('config.yaml', encoding='utf8') config = yaml.load(f) self.PTTBot = PTT.Library(config['account'], config['password'], kickOtherLogin=False) if not self.PTTBot.isLoginSuccess(): self.PTTBot.Log('登入失敗')
def Init(): print('===正向===') print('===預設值===') PTT.Library() print('===中文顯示===') PTT.Library(Language=PTT.Language.Chinese) print('===英文顯示===') PTT.Library(Language=PTT.Language.English) print('===Telnet===') PTT.Library(ConnectMode=PTT.ConnectMode.Telnet) print('===WebSocket===') PTT.Library(ConnectMode=PTT.ConnectMode.WebSocket) print('===Log DEBUG===') PTT.Library(LogLevel=PTT.LogLevel.DEBUG) print('===Log INFO===') PTT.Library(LogLevel=PTT.LogLevel.INFO) print('===Log SLIENT===') PTT.Library(LogLevel=PTT.LogLevel.SLIENT) print('===Log SLIENT======') print('===負向===') try: print('===語言 99===') PTT.Library(Language=99) except ValueError: print('通過') except: print('沒通過') return print('===語言放字串===') try: PTT.Library(Language='PTT.Language.English') except TypeError: print('通過') except: print('沒通過') return
def ThreadFunc1(): ThreadBot1 = PTT.Library() try: ThreadBot1.login( ID1, Password1, # KickOtherLogin=True ) except PTT.Exceptions.LoginError: ThreadBot1.log('登入失敗') return ThreadBot1.logout() print('1 多線程測試完成')
def ThreadFunc2(): ThreadBot2 = PTT.Library() try: ThreadBot2.login( ID2, Password2, # KickOtherLogin=True ) except PTT.Exceptions.LoginError: ThreadBot2.log('登入失敗') return ThreadBot2.logout() print('2 多線程測試完成')
def LogHandlerDemo(): def handler(Msg): with open('LogHandler.txt', 'a', encoding='utf-8') as F: F.write(Msg + '\n') PTTBot = PTT.Library(LogHandler=handler) try: PTTBot.login(ID, Password) except PTT.Exceptions.LoginError: PTTBot.log('登入失敗') return PTTBot.log('登入成功') PTTBot.logout() sys.exit()
def ThreadFunc(): global PTTBot PTTBot = PTT.Library( ConnectMode=PTT.ConnectMode.WebSocket, LogLevel=PTT.LogLevel.TRACE, # LogLevel=PTT.LogLevel.DEBUG, ) try: PTTBot.login( ID, Password, # KickOtherLogin=True ) except PTTLibrary.Exceptions.LoginError: PTTBot.log('登入失敗') return print('多線程測試完成')
def ThreadFunc(): global ThreadBot ThreadBot = PTT.Library( # LogLevel=PTT.LogLevel.TRACE, # LogLevel=PTT.LogLevel.DEBUG, ) try: ThreadBot.login( ID, Password, # KickOtherLogin=True ) except PTT.Exceptions.LoginError: ThreadBot.log('登入失敗') return ThreadBot.logout() print('多線程測試完成')
def __init__(self, outputPath): try: with open('Account.txt') as AccountFile: Account = json.load(AccountFile) ID = Account['ID'] Password = Account['Password'] except FileNotFoundError: ID = input('請輸入帳號: ') Password = getpass.getpass('請輸入密碼: ') self.PTTBot = PTT.Library(kickOtherLogin=False) ErrCode = self.PTTBot.login(ID, Password) if ErrCode != PTT.ErrorCode.Success: self.PTTBot.Log('登入失敗') sys.exit() self.timing = 'intrade' self.famelist = [] self.outputPath = outputPath
def __init__(self): try: with open('Account.txt') as AccountFile: Account = json.load(AccountFile) ID = Account['ID'] Password = Account['Password'] except FileNotFoundError: ID = input('請輸入帳號: ') Password = getpass.getpass('請輸入密碼: ') self.PTTBot = PTT.Library(kickOtherLogin=False) ErrCode = self.PTTBot.login(ID, Password) if ErrCode != PTT.ErrorCode.Success: self.PTTBot.Log('登入失敗') sys.exit() self.Board = PTTBoard() self.CrawPost = 0 self.RepoNum = 0 self.PromNum = 0 self.OtherNum = 0
PTTBot.Log('爬行成功共 ' + str(SuccessCount) + ' 篇文章 共有 ' + str(DeleteCount) + ' 篇文章被刪除') #使用Account.txt來讀入帳號密碼 try: with open('Account.txt') as AccountFile: Account = json.load(AccountFile) ID = Account['ID'] Password = Account['Password'] except FileNotFoundError: ID = input('請輸入帳號: ') Password = getpass.getpass('請輸入密碼: ') #是否要在登入時踢掉其他登入? PTTBot = PTT.Library(kickOtherLogin=True) #登入 ErrCode = PTTBot.login(ID, Password) #使用錯誤碼,判斷登入是否成功 if ErrCode != PTT.ErrorCode.Success: PTTBot.Log('登入失敗') sys.exit() try: CrawlBoard() pass except Exception as e: traceback.print_tb(e.__traceback__) print(e) PTTBot.Log('接到例外 啟動緊急應變措施')
if len(sys.argv) == 2: if sys.argv[1] == '-ci': print('CI test run success!!') sys.exit() try: with open('Account.txt') as AccountFile: Account = json.load(AccountFile) ID = Account['ID'] Password = Account['Password'] except FileNotFoundError: ID = input('請輸入帳號: ') Password = getpass.getpass('請輸入密碼: ') PTTBot = PTT.Library(ID, Password, kickOtherLogin=False) if not PTTBot.isLoginSuccess(): PTTBot.Log('登入失敗') sys.exit() # PTTBot.setLogLevel(PTTBot.LogLevel_DEBUG) # GetNewestPostIndexDemo() # PostDemo() # GetPostInfoDemo() # PushDemo() # GetNewPostIndexListDemo() # MailDemo() # GetTimeDemo() # GetUserInfoDemo() # GiveMoneyDemo() # CrawlBoardDemo()
print(f'收到來自 {Target} 的水球 [{Content}]') print('=' * 30) if __name__ == '__main__': os.system('cls') print('Welcome to PTT Library v ' + PTT.Version + ' Echo Server') ID, Password = getPW() try: PTTBot = PTT.Library( # LogLevel=PTT.LogLevel.TRACE, ) try: PTTBot.login(ID, Password, KickOtherLogin=True) except PTTLibrary.Exceptions.LoginError: PTTBot.log('登入失敗') sys.exit() Echo() # listWaterBall() except Exception as e: traceback.print_tb(e.__traceback__) print(e)
if __name__ == '__main__': st = datetime.datetime.fromtimestamp(time.time()).strftime('%y%m%d') title = '[LIVE] ' + st + ' Showroom & 浪直播 實況閒聊文' contents = Showroom.get_content() print(contents) exit() ### 發文相關資訊填寫 ID = PTT_ACCOUNT Password = PTT_PASSWORD board = 'AKB48' KickOtherLogin = False ### PTTBot = PTT.Library(kickOtherLogin=KickOtherLogin) ErrCode = PTTBot.login(ID, Password) if ErrCode != PTT.ErrorCode.Success: PTTBot.Log('登入失敗') sys.exit() ErrorCode = PTTBot.post(board, title, contents, 0, 0) if ErrorCode == PTT.ErrorCode.Success: PTTBot.Log('在' + board + '板發文成功') elif ErrorCode == PTT.ErrorCode.NoPermission: PTTBot.Log('發文權限不足') else: PTTBot.Log('在 Test 板發文失敗')
import sys from PTTLibrary import PTT import json import numpy as np import pandas as pd print('import end') #Initial Global Param PTTBot=PTT.Library(kickOtherLogin=False) pushBoundary=0 Board='Testtttt' StartIndex=0 EndIndex=0 showPushTime=False GapPrint=0 GapBoundary=0 Month={'Jan':1,'Feb':2,'Mar':3,'Apr':4,'May':5,'Jun':6,'Jul':7,'Aug':8,'Sep':9,'Oct':10,'Nov':11,'Dec':12} #Read Setting def readSettings(): setting=[] st=pd.read_json('./settings.json') setting.append(st["ID"].values[0]) setting.append(st["Password"].values[0]) global pushBoundary,Board,StartIndex,EndIndex,showPushTime,GapPrint,GapBoundary
WantList.append(line.replace('\n', '').replace('\r', '')) HelloList = [] with open('HelloList.txt', encoding='utf-8-sig') as fp: for line in fp: if len(line) == 0: continue HelloList.append(line.replace('\n', '').replace('\r', '')) PublicList = [] with open('PublicList.txt', encoding='utf-8-sig') as fp: for line in fp: if len(line) == 0: continue PublicList.append(line.replace('\n', '').replace('\r', '')) PTTCrawler = PTT.Library(ID, Password, False) if not PTTCrawler.isLoginSuccess(): PTTCrawler.Log('Login fail') else: #PTTCrawler.setLogLevel(PTTCrawler.LogLevel_DEBUG) LastIndex = 0 LastIndexList = [0] NoFastPushWait = False First = True PTTCrawler.Log('Start detect new post in ' + Board) while Retry: try: ErrorCode, Time = PTTCrawler.getTime()
if len(sys.argv) == 2: if sys.argv[1] == '-ci': print('CI test run success!!') sys.exit() try: with open('Account.txt') as AccountFile: Account = json.load(AccountFile) ID = Account['ID'] Password = Account['Password'] except FileNotFoundError: ID = input('請輸入帳號: ') Password = getpass.getpass('請輸入密碼: ') # PTTBot = PTT.Library(ID, Password, kickOtherLogin=False, _LogLevel=PTT.LogLevel.DEBUG) PTTBot = PTT.Library(ID, Password, WaterBallHandler=WaterBallHandler) # PTTBot = PTT.Library(ID, Password) ErrCode = PTTBot.login() if ErrCode != PTT.ErrorCode.Success: PTTBot.Log('登入失敗') sys.exit() try: # PostDemo() # PushDemo() # GetNewestIndexDemo() # GetPostDemo() # MailDemo() # GetTimeDemo() # GetMailDemo()
Check = 1 break # 離開for迴圈 else: pass # 登入 try: with open('Account.json') as AccountFile: Account = json.load(AccountFile) ID = Account['ID'] Password = Account['Password'] except FileNotFoundError: ID = input('請輸入帳號: ') Password = getpass.getpass('請輸入密碼: ') PTTBot = PTT.Library(ID, Password, kickOtherLogin=False, _LogLevel=PTT.LogLevel.DEBUG) # 推文範例 # PTTBot.push(Board, PTT.PushType.Arrow, 'PTT Library Push API 4', PostIndex=470) # PTTBot.push(Board, PTT.PushType.Arrow, 'PTT Library Push API 4', '#1RF7DoYg') try: # 前置設定 Board = 'TEST' # 看板 PostIndex = 624 # 文章號碼 PTTBot.gotoBoard(Board) PTTBot.gotoArticle(PostIndex) PTTBot.push(Board, PTT.PushType.Arrow, '遊戲開始!', PostIndex=PostIndex) # 主要遊戲內容
print('Please note PTT ID and Password in Account.txt') print('{"ID":"YourID", "Password":"******"}') sys.exit() return ID, Password ID, Password = getPW() try: # Loginout() # ThreadingTest() ptt_bot = PTT.Library( # LogLevel=PTT.LogLevel.TRACE, # LogLevel=PTT.LogLevel.DEBUG, # Host=PTT.Host.PTT2 ) try: ptt_bot.login( ID, Password, # KickOtherLogin=True ) pass except PTT.Exceptions.LoginError: ptt_bot.log('登入失敗') sys.exit() BoardList = ptt_bot.getBoardList() # print(' '.join(BoardList))
print('Welcome to PTT Library v ' + PTT.Version + ' test case') if len(sys.argv) == 2: if sys.argv[1] == '-ci': print('CI test run success!!') sys.exit() ID, Password = getPW() try: # Loginout() # PerformanceTest() # ThreadingTest() PTTBot = PTT.Library( # LogLevel=PTT.LogLevel.TRACE, # LogLevel=PTT.LogLevel.DEBUG, ) try: PTTBot.login(ID, Password, KickOtherLogin=True) except PTT.Exceptions.LoginError: PTTBot.log('登入失敗') sys.exit() # GetPost() # GetPostWithCondition() # Post() # GetNewestIndex() CrawlBoard() # CrawlBoardWithCondition() # Push() # GetUser()
if sys.argv[1] == '-ci': print('CI test run success!!') sys.exit() try: with open('Account.txt') as AccountFile: Account = json.load(AccountFile) ID = Account['ID'] Password = Account['Password'] except FileNotFoundError: ID = input('請輸入帳號: ') Password = getpass.getpass('請輸入密碼: ') # PTTBot = PTT.Library(ID, Password, kickOtherLogin=False, _LogLevel=PTT.LogLevel.DEBUG) # PTTBot = PTT.Library(ID, Password, WaterBallHandler=WaterBallHandler) PTTBot = PTT.Library(ID, Password, _LogLevel=PTT.LogLevel.DEBUG) ErrCode = PTTBot.login() if ErrCode != PTT.ErrorCode.Success: PTTBot.Log('登入失敗') sys.exit() try: # PostDemo() # PushDemo() # GetNewestIndexDemo() # GetPostDemo() # MailDemo() # GetTimeDemo() # GetMailDemo() # GetUserDemo()
if len(sys.argv) == 2: if sys.argv[1] == '-ci': print('CI test run success!!') sys.exit() ID, Password = getPW() try: # Loginout() # PerformanceTest() # ThreadingTest() PTTBot = PTT.Library( ConnectMode=PTT.ConnectMode.WebSocket, # LogLevel=PTT.LogLevel.TRACE, # LogLevel=PTT.LogLevel.DEBUG, ) try: PTTBot.login( ID, Password, # KickOtherLogin=True ) except PTTLibrary.Exceptions.LoginError: PTTBot.log('登入失敗') sys.exit() # GetPost() # GetPostWithCondition() # Post()
Password = Account['Password'] except FileNotFoundError: ID = input('請輸入帳號: ') Password = getpass.getpass('請輸入密碼: ') # 不會把重複的登入踢掉,設定 Log level 為 除錯等級 # PTTBot = PTT.Library(ID, Password, kickOtherLogin=False, _LogLevel=PTT.LogLevel.DEBUG) # 水球接收器,不過沒長時間測試,大量API呼叫的時候可能不穩 # PTTBot = PTT.Library(ID, Password, WaterBallHandler=WaterBallHandler) # PTTBot = PTT.Library(ID, Password, _LogLevel=PTT.LogLevel.DEBUG) # Log 接收器,如果有需要把內部顯示抓出來的需求可以用這個 # PTTBot = PTT.Library(ID, Password, LogHandler=LogHandler) # 如果您的網路連線品質不佳,可以試著調整連線等待時間參數 # PTTBot = PTT.Library(ID, Password, PreWait=0.1, EveryWait=0.2, MaxEveryWait=1, MinEveryWait=1) PTTBot = PTT.Library(ID, Password) ErrCode = PTTBot.login() if ErrCode != PTT.ErrorCode.Success: PTTBot.Log('登入失敗') sys.exit() try: # PostDemo() # PushDemo() # GetNewestIndexDemo() # GetPostDemo() # MailDemo() # GetTimeDemo() # GetMailDemo() # GetUserDemo()
if len(sys.argv) == 2: if sys.argv[1] == '-ci': print('CI test run success!!') sys.exit() ID, Password = getPW() try: # Loginout() # PerformanceTest() # ThreadingTest() PTTBot = PTT.Library( LogLevel=PTT.LogLevel.TRACE, # LogLevel=PTT.LogLevel.DEBUG, Host=PTT.Host.PTT2 ) try: PTTBot.login( ID, Password, # KickOtherLogin=True ) pass except PTT.Exceptions.LoginError: PTTBot.log('登入失敗') sys.exit() # GetPost() # GetPostWithCondition()
from PTTLibrary import PTT # 讀取 config.ini config = configparser.ConfigParser() config.read('config.ini', encoding='UTF-8') # 設定參數 Username = str(config['DEFAULT']['Username']) Password = str(config['DEFAULT']['Password']) LineAPI = str(config['DEFAULT']['LineAPI']) RefreshInterval = int(config['DEFAULT']['RefreshInterval']) LineContent = str(config['DEFAULT']['LineContent']) BoardFilterDict = dict(config._sections['BOARD']) # 宣告 PTTBot & 登入 PTTBot = PTT.Library() LoginStatus = PTTBot.login(Username, Password) if LoginStatus != PTT.ErrorCode.Success: PTTBot.Log('登入失敗') sys.exit() # 時間戳 def timestamp(): ts = '[' + datetime.datetime.now().strftime("%m-%d %H:%M:%S") + ']' return ts # 利用 Line Notify 功能達成推送訊息 def sendMessage(message): url = 'https://notify-api.line.me/api/notify'
def SendMessageDemo(): # 此指令可以讓開發者自行開發送給 PTT 的指令,並根據回傳畫面做出相對應的回應 ################## 操作指令資訊 Command information ################## # 讓畫面回到最上層主選單 # GotoMainMenuCommand # 更新 PTT 畫面,預設已經會做更新畫面 # 拉出來才發現預設了,對不起 請忽略我的恍神 # RefreshCommand # 上下左右方向鍵的操作 # MoveUpCommand # MoveDownCommand # MoveRightCommand # MoveLeftCommand # 如有未盡操作,請參考 # http://www.physics.udel.edu/~watson/scen103/ascii.html # 如果你想為這個專案做出貢獻,那就送出你的 pull request 吧 # 每個 request 都會被我檢視整理後整入主線 Message = PTT.MoveUpCommand # 你應該在 DetectTargetList 實作出應對所有情況的 DetectUnit # 並且至少要有一個 DetectUnit 具備出口 ( BreakDetect=True 和 ErrCode = 你想要的錯誤碼 ) DetectTargetList = [ PTT.DetectUnit( '更新 PTT 畫面', '我是' + ID, PTT.ResponseUnit(PTT.GotoMainMenuCommand, True), # 具備 BreakDetect=True 的 DetectUnit 會被視為出口 BreakDetect=True, ErrCode = PTT.ErrorCode.Success ), PTT.PTTBUGDetectUnit ] isBreakDetect = False while not isBreakDetect: ErrCode, CatchIndex = PTTBot.operatePTT(Message) if ErrCode == PTT.ErrorCode.WaitTimeout: PTTBot.Log('操作超時重新嘗試') return elif ErrCode != PTT.ErrorCode.Success: PTTBot.Log('操作失敗 錯誤碼: ' + str(ErrCode)) return isDetectedTarget = False for DetectTarget in DetectTargetList: if DetectTarget.isMatch(PTTBot.ReceiveData): isDetectedTarget = True if DetectTarget.isBreakDetect(): isBreakDetect = True ErrCode = DetectTarget.getErrorCode() break break if not isDetectedTarget: PTTBot.showScreen(ErrCode, sys._getframe().f_code.co_name) PTTBot.Log('無法解析的狀態! PTT Library 緊急停止') PTTBot.logout() sys.exit() PTTBot.showScreen(ErrCode, sys._getframe().f_code.co_name)