def handleTask(self, task): if task.name == 'login': level = PTT.log.level.INFO if self.enable_trace: level = PTT.log.level.TRACE self.ptt_bot = PTT.API(log_handler=self.logHandler, log_level=level) try: self.ptt_bot.login(self.ptt_id, self.password) self.msg.emit('登入成功') self.signal.emit(LoginSuccess) except: self.signal.emit(LoginFailed) self.msg.emit('登入失敗') elif task.name == 'push': self.push(task.kwargs['board'], task.kwargs['post_index'], task.kwargs['text']) elif task.name == 'sendMails': self.sendMails(task.kwargs['mails'], task.kwargs['backup']) elif task.name == 'editPost': self.editPost(task.kwargs['board'], task.kwargs['post_index'], task.kwargs['edit_msg']) elif task.name == 'changeLoglevel': self.setLogLevelToTrace(task.kwargs['toTrace']) elif task.name == 'giveMoney': self.giveMoney(task.kwargs['amount'], task.kwargs['receivers'], task.kwargs['edit_bag'], task.kwargs['bag_title'], task.kwargs['bag_content']) elif task.name == 'giveDifferentMoney': self.giveDifferentMoney(task.kwargs['receivers_and_amount'], task.kwargs['edit_bag'], task.kwargs['bag_title'], task.kwargs['bag_content'])
def watch(self): watch_bot = PTT.API(log_level=PTT.log.level.SILENT) watch_bot.login(id, pw) refresh = True while True: if refresh: os.system('cls') print('目標: ', self.target) print('IP 清單: ', '\n'.join(self.ip_list)) print('可能分身清單: ', ' '.join(self.possible_list)) print('====================================') refresh = False target_info = watch_bot.get_user(self.target) if target_info.last_ip not in self.ip_list: print('find new ip', target_info.last_ip) self.ip_list.add(target_info.last_ip) time.sleep(3) if target_info.last_ip not in self.ip_list: refresh = True watch_bot.logout()
def login(): ptt_bot = PTT.API( log_level=PTT.log.level.SILENT, # log_level=PTT.log.level.TRACE, # log_level=PTT.log.level.DEBUG, # host=PTT.data_type.host_type.PTT2 # log_handler=handler # for 本機測試 # connect_mode=PTT.connect_core.connect_mode.TELNET, # host=PTT.data_type.host_type.LOCALhost, # port=8888, ) try: ptt_bot.login( ptt_id, password, # kick_other_login=True ) except PTT.exceptions.LoginError: ptt_bot.log('登入失敗') sys.exit() except PTT.exceptions.WrongIDorPassword: ptt_bot.log('帳號密碼錯誤') sys.exit() except PTT.exceptions.LoginTooOften: ptt_bot.log('請稍等一下再登入') sys.exit() ptt_bot.set_call_status(PTT.data_type.call_status.OFF) return ptt_bot
def thread_func1(): thread_bot1 = PTT.API() try: thread_bot1.login( id1, password1, # kick_other_login=True ) except PTT.exceptions.LoginError: thread_bot1.log('登入失敗') return thread_bot1.logout() print('1 多線程測試完成')
def thread_func2(): thread_bot2 = PTT.API() try: thread_bot2.login( id2, password2, # kick_other_login=True ) except PTT.exceptions.LoginError: thread_bot2.log('登入失敗') return thread_bot2.logout() print('2 多線程測試完成')
def init(): print('===正向===') print('===預設值===') PTT.API() print('===中文顯示===') PTT.API(language=PTT.i18n.language.CHINESE) print('===英文顯示===') PTT.API(language=PTT.i18n.language.ENGLISH) print('===log DEBUG===') PTT.API(log_level=PTT.log.level.DEBUG) print('===log INFO===') PTT.API(log_level=PTT.log.level.INFO) print('===log SLIENT===') PTT.API(log_level=PTT.log.level.SILENT) print('===log SLIENT======') print('===負向===') try: print('===語言 99===') PTT.API(language=99) except ValueError: print('通過') except: print('沒通過') sys.exit(-1) print('===語言放字串===') try: PTT.API(language='PTT.i18n.language.ENGLISH') except TypeError: print('通過') except: print('沒通過') sys.exit(-1) def handler(msg): with open('log.txt', 'a', encoding='utf-8') as f: f.write(msg + '\n') ptt_bot = PTT.API( log_handler=handler) ptt_bot.log('Test log')
def search(self): search_bot = PTT.API(log_level=PTT.log.level.SILENT) search_bot.login(self.id, self.pw) case_list = list(string.ascii_lowercase) random.shuffle(case_list) while True: for c in case_list: id_list = search_bot.search_user(c) random.shuffle(id_list) for current_user in id_list: current_user_info = search_bot.get_user(current_user) print('比對', current_user) if current_user_info.last_ip in self.ip_list: self.possible_list.append(current_user)
def run(self): self.ptt_bot = PTT.API(log_level=PTT.log.level.INFO) loginSuccess = self.login() if not loginSuccess: return # start to get posts while True: try: post_info = self.ptt_bot.get_post(self.board, post_aid=self.aid) self.titleSignal.emit(post_info.title) totalPosts = len(post_info.push_list) if totalPosts <= self.index: continue if totalPosts - self.index > 30: self.index = totalPosts - 30 newPosts = post_info.push_list[self.index:] for push_info in newPosts: floor = self.index + 1 pushType = '推' if push_info == PTT.data_type.push_type.BOO: pushType = '噓' elif push_info == PTT.data_type.push_type.ARROW: pushType = '->' author = push_info.author content = push_info.content pushTime = push_info.time info = str(floor) + 'F: ' + pushType + ' ' + author # buffer = str(floor) + 'F: ' + pushType + ' ' + author + '\n ' + content #buffer = util.SetPushFormat(floor,pushType, author, pushTime, content) self.index = floor self.infoSignal.emit(info) self.postSignal.emit(content) except PTT.exceptions.ConnectionClosed: self.login() except Exception as e: status = "unknown error" error_class = e.__class__.__name__ logging.warning(str(e)) break time.sleep(1) # load new posts every 1 second
def __init__(self, id, pw, target): self.id = id self.pw = pw ptt_bot = PTT.API() ptt_bot.login(id, pw, kick_other_login=True) target_info = ptt_bot.get_user(target) self.target = target ptt_bot.logout() self.ip_list = set() self.ip_list.add(target_info.last_ip) self.possible_list = list() watch_thread = threading.Thread(target=self.watch) watch_thread.start() search_thread = threading.Thread(target=self.search) search_thread.start()
def crawl_worker(self, id, pw, board, start_index, end_index): ptt_bot = PTT.API() ptt_bot.login(id, pw) for index in range(start_index, end_index + 1): try: post_info = ptt_bot.get_post(board, post_index=index) except: print('get_post error', index) continue if post_info is None: continue if post_info.date is None: print('aid', post_info.aid) print('內文', post_info.content) print('===========') continue # print(post_info.title) try: date = post_info.date.split(' ') date.pop(0) date.insert(0, date[-1]) date.pop() date = [x for x in date if len(x) != 0] if len(date[2]) == 1: date[2] = '0' + date[2] file_name = '_'.join(date).replace(':', '.') + '.json' if len(file_name) != 25: print('aid', post_info.aid) print('file name error', file_name) print('date error', post_info.date) print('===========') continue except: print('aid', post_info.aid) print('date error', post_info.date) print('===========') continue data = dict() data['aid'] = post_info.aid data['author'] = post_info.author data['title'] = post_info.title data['date'] = post_info.date data['location'] = post_info.location data['content'] = post_info.content data['ip'] = post_info.ip push_list = list() for push in post_info.push_list: current_push = dict() current_push['author'] = push.author current_push['content'] = push.content current_push['time'] = push.time push_list.append(current_push) data['push_list'] = push_list if os.path.isfile(f'LAW/{file_name}'): continue with open(f'LAW/{file_name}', 'w', encoding='utf-8') as f: json.dump(data, f, ensure_ascii=False, indent=4) # print(file_name) # Do anything you want here!!! ptt_bot.logout()
def change_pw(): ptt_bot.change_pw(password) if __name__ == '__main__': print('Welcome to PyPtt v ' + PTT.version.V + ' test case') try: # init() # threading_test() ptt_bot = PTT.API( # log_level=PTT.log.level.TRACE, # log_level=PTT.log.level.DEBUG, # host=PTT.data_type.host_type.PTT2 # for 本機測試 # connect_mode=PTT.connect_core.connect_mode.TELNET, # host=PTT.data_type.host_type.LOCALHOST, # port=8888, # language=PTT.i18n.language.ENGLISH ) if ptt_bot.config.host == PTT.data_type.host_type.PTT1: ptt_id, password = get_password('test_account_1.txt') else: ptt_id, password = get_password('test_account_2.txt') try: ptt_bot.login( ptt_id, password, # kick_other_login=True
from PyPtt import PTT ptt_bot = PTT.API(host=PTT.data_type.host_type.PTT2) post_info = ptt_bot.get_post('Python', post_index=7486)
def run(self): ptt_bot = PTT.API() while True: if self.catch_error: self.catch_error = False current_pw = current_otp else: current_pw = self.ptt_pw self.login_finish = False while True: try: ptt_bot.login( self.ptt_id, current_pw, kick_other_login=True ) except PTT.exceptions.WrongIDorPassword: ptt_bot.log('帳號密碼錯誤') self.console.system_alert('帳號密碼錯誤') self.login_finish = True return except PTT.exceptions.LoginError: ptt_bot.log('登入失敗') self.console.system_alert('登入失敗') self.login_finish = True return except PTT.exceptions.LoginTooOften: ptt_bot.log('請稍等一下再登入') self.console.system_alert('請稍等一下再登入') self.login_finish = True return except PTT.exceptions.ConnectError: ptt_bot.log('連線有問題') self.console.system_alert('連線有問題') self.login_finish = True return break self.login_finish = True self.console.ptt_id = self.ptt_id self.login_success = True last_otp = '' while not self.call_logout: time.sleep(0.1) if self.otp is not None: current_otp = self.otp.now() if last_otp != current_otp: self.logger.show_value(Logger.INFO, '新密碼', current_otp) try: if self.console.test_mode: ptt_bot.change_pw(self.ptt_pw) else: ptt_bot.change_pw(current_otp) except PTT.exceptions.ConnectionClosed: self.catch_error = True break except PTT.exceptions.Timeout: self.catch_error = True break self.console.config.set(config.key_current_otp, current_otp) self.console.config.set(config.key_last_otp, last_otp) self.console.config.write() self.console.current_otp = current_otp if self.console.otp_form is not None: self.console.otp_form.update_otp() last_otp = current_otp self.logger.show(Logger.INFO, '密碼變更完成') if self.catch_error: continue if self.otp is not None: ptt_bot.change_pw(self.ptt_pw) break self.logger.show(Logger.INFO, '1') ptt_bot.logout() self.logger.show(Logger.INFO, '4') self.reset()
# target = waterball.target # content = waterball.content # # print(f'收到來自 {target} 的水球 [{content}]') # # print('=' * 30) if __name__ == '__main__': print('Welcome to PyPtt v ' + PTT.version.V + ' Echo Server') ptt_id, password = get_pw() try: ptt_bot = PTT.API( # log_level=PTT.log_level.TRACE, ) try: ptt_bot.login(ptt_id, password, kick_other_login=True) except PTTLibrary.exceptions.LoginError: ptt_bot.log('登入失敗') sys.exit() echo() # listWaterBall() except Exception as e: traceback.print_tb(e.__traceback__) print(e)
#!/usr/bin/env python #coding=utf-8 import json from PyPtt import PTT import re ######################## ptt_bot = PTT.API(language=PTT.i18n.language.CHINESE) ptt_id = 'abc' password = '******' def lambda_handler(event, context): #print("Received event: " + json.dumps(event, indent=2)) info = {} print("[debuging]: ", event) try: target_board = event['board'] read_article_number = event['num'] if int(read_article_number) > 5: read_article_number = 5 info['error'] = 'false' except: target_board = '' if target_board == '': target_board = 'Soft_Job'
def run(self): self.bot = PTT.API() herald = self.herald cond = herald.cond cond.acquire() while True: # try to login while herald.cmd != 'login': herald.set_status(False, 'Please login first') cond.notify() cond.wait() self.cmd_login() cond.notify() if herald.status['status']: # if login successfully herald.timeout = True cond.wait(self.timeout_sec) already_logout = False while herald.cmd != 'logout' and not herald.timeout: try: if herald.cmd == 'get_fav_board': self.cmd_get_fav_board() elif herald.cmd == 'get_board_list': self.cmd_get_board_list() elif herald.cmd == 'get_post': self.cmd_get_post() elif herald.cmd == 'get_posts': self.cmd_get_posts() elif herald.cmd == 'get_posts_quick': self.cmd_get_posts(quick=True) elif herald.cmd == 'add_push': self.cmd_add_push() elif herald.cmd == 'add_post': self.cmd_add_post() elif herald.cmd == 'prevent_logout': self.cmd_get_fav_board() # add other PTT commands here else: herald.set_status(False, 'No this command') except Exception as e: e_str = self.except_handle(e) self.bot.log('[except]' + e_str) herald.set_status(False, e_str) if e in [ PTT.exceptions.LoginError, PTT.exceptions.NoSuchUser, # PTT.exceptions.RequireLogin, PTT.exceptions.UserOffline, PTT.exceptions.ConnectionClosed, PTT.exceptions.UnregisteredUser, PTT.exceptions.WrongIDorPassword, PTT.exceptions.LoginTooOften, PTT.exceptions.WrongPassword ]: herald['need_relogin'] = True already_logout = True break herald.timeout = True cond.notify() cond.wait(self.timeout_sec) if not already_logout: try: self.cmd_logout() except Exception as e: e_str = self.except_handle(e) self.bot.log('[except]' + e_str) herald.set_status(False, e_str) herald.glb_list['used'].pop(herald.id, None) herald.glb_list['available'].append(herald) if herald.timeout: herald.sql_log(action='timeout', wapp=False) else: cond.notify() # wait for another login cond.wait() cond.notify() cond.release()
def run_on_ptt_2(): ptt_bot_0 = PTT.API(host=PTT.data_type.host_type.PTT2, log_handler=log) ptt_bot_1 = PTT.API(host=PTT.data_type.host_type.PTT2, log_handler=log) case(ptt_bot_0, ptt_bot_1)
return ptt_id, password if __name__ == '__main__': with open('check.json', 'r', encoding='utf-8') as f: data = json.loads(f.read()) current_board = data['BoardInfo']['Name'] # print(current_board) ptt_id, password = get_password('Account.txt') try: ptt_bot = PTT.API() try: ptt_bot.login( ptt_id, password, # kick_other_login=True ) except PTT.exceptions.LoginError: ptt_bot.log('登入失敗') sys.exit() except PTT.exceptions.WrongIDorPassword: ptt_bot.log('帳號密碼錯誤') sys.exit() except PTT.exceptions.LoginTooOften: ptt_bot.log('請稍等一下再登入') sys.exit()
import sys import os import time import json import traceback from PyPtt import PTT ptt_id, ptt_pw = 'PTT id', 'PTT pw' release = False if __name__ == '__main__': os.system('cls') time_bot = PTT.API() try: time_bot.login(ptt_id, ptt_pw, kick_other_login=True) time_bot.logout() except PTT.exceptions.LoginError: time_bot.log('登入失敗 ' + ptt_id) sys.exit() time_bot = PTT.API() time_bot.login(ptt_id, ptt_pw) if release: target_pre_time = '23:59' current_board = 'Gossiping' title = '請問有2021首PO的八卦嗎?' content = PTT.command.Ctrl_Y * 9 + '''不好意思,搶到首PO
def test_init(): log('init', mode='w') log('===正向===') log('===預設值===') PTT.API() log('===中文顯示===') PTT.API(language=PTT.i18n.language.CHINESE) log('===英文顯示===') PTT.API(language=PTT.i18n.language.ENGLISH) log('===log DEBUG===') PTT.API(log_level=PTT.log.level.DEBUG) log('===log INFO===') PTT.API(log_level=PTT.log.level.INFO) log('===log SLIENT===') PTT.API(log_level=PTT.log.level.SILENT) log('===log SLIENT======') log('===負向===') try: log('===語言 99===') PTT.API(language=99) except ValueError: log('通過') except: log('沒通過') sys.exit(-1) log('===語言放字串===') try: PTT.API(language='PTT.i18n.language.ENGLISH') except TypeError: log('通過') except: log('沒通過') sys.exit(-1) def handler(msg): with open('log.txt', 'a', encoding='utf-8') as f: f.write(msg + '\n') ptt_bot = PTT.API(log_handler=handler) ptt_bot.log('Test log') global run_ci global automation_ci global ptt_id_0 global ptt_pw_0 global ptt2_id_0 global ptt2_pw_0 global current_py_version global ptt_id_1 global ptt_pw_1 global ptt2_id_1 global ptt2_pw_1 run_ci = False automation_ci = False if '-ci' in sys.argv: run_ci = True load_from_file = False if run_ci: ptt_id_0 = os.getenv('PTT_ID_0') ptt_pw_0 = os.getenv('PTT_PW_0') ptt_id_1 = os.getenv('PTT_ID_1') ptt_pw_1 = os.getenv('PTT_PW_1') ptt2_id_0 = os.getenv('PTT2_ID_0') ptt2_pw_0 = os.getenv('PTT2_PW_0') ptt2_id_1 = os.getenv('PTT2_ID_1') ptt2_pw_1 = os.getenv('PTT2_PW_1') if ptt_id_0 is None or ptt_pw_0 is None: log('從環境變數取得帳號密碼失敗') load_from_file = True automation_ci = False else: automation_ci = True else: load_from_file = True if load_from_file: ptt_id_0, ptt_pw_0 = get_password('test_account_0.txt') ptt_id_1, ptt_pw_1 = get_password('test_account_1.txt') ptt2_id_0, ptt2_pw_0 = get_password('test_account_2.txt') ptt2_id_1, ptt2_pw_1 = get_password('test_account_3.txt') current_py_version = os.getenv('PYTHON_VERSION') if current_py_version is None: current_py_version = sys.version[:3]
print('find {} push\n'.format(len(push_id_set))) push_id_list = list(push_id_set)[:floor] # random choice atari = list(random.sample(push_id_list, k=samples)) atari.sort() # get ids for a in atari: print(a) print("恭喜以上 id 中獎,開始發錢\n") # login ptt_bot = PTT.API(screen_time_out=5, log_level=PTT.log.level.TRACE) password = getpass() try: ptt_bot.login(ptt_id, password) except PTT.exceptions.LoginError: ptt_bot.log('登入失敗') sys.exit() except PTT.exceptions.WrongIDorPassword: ptt_bot.log('帳號密碼錯誤') sys.exit() except PTT.exceptions.LoginTooOften: ptt_bot.log('請稍等一下再登入') sys.exit() ptt_bot.log('登入成功') # give money
class DataThread(QThread ): # ref https://www.cnblogs.com/linyfeng/p/12239856.html statusSignal = pyqtSignal(str) titleSignal = pyqtSignal(str) postSignal = pyqtSignal(str) infoSignal = pyqtSignal(str) ptt_bot = PTT.API() def __init__(self): super().__init__() self.index = 0 def setting(self, id, password, board, aid): self.id = id self.password = password self.board = board self.aid = aid def login(self): status = "登入中" try: self.ptt_bot.login(self.id, self.password) except PTT.exceptions.LoginError: status = "登入失敗" except PTT.exceptions.WrongIDorPassword: status = "帳號或密碼錯誤" except PTT.exceptions.LoginTooOften: status = "請稍後再登入" except Exception as e: status = "unknown error" error_class = e.__class__.__name__ logging.warning(str(e)) else: status = "登入成功: " + self.id util.SaveUserJson(self.id, self.password, self.board, self.aid) self.statusSignal.emit(status) if status.startswith("登入成功"): return True return False def run(self): self.ptt_bot = PTT.API(log_level=PTT.log.level.INFO) loginSuccess = self.login() if not loginSuccess: return # start to get posts while True: try: post_info = self.ptt_bot.get_post(self.board, post_aid=self.aid) self.titleSignal.emit(post_info.title) totalPosts = len(post_info.push_list) if totalPosts <= self.index: continue if totalPosts - self.index > 30: self.index = totalPosts - 30 newPosts = post_info.push_list[self.index:] for push_info in newPosts: floor = self.index + 1 pushType = '推' if push_info == PTT.data_type.push_type.BOO: pushType = '噓' elif push_info == PTT.data_type.push_type.ARROW: pushType = '->' author = push_info.author content = push_info.content pushTime = push_info.time info = str(floor) + 'F: ' + pushType + ' ' + author # buffer = str(floor) + 'F: ' + pushType + ' ' + author + '\n ' + content #buffer = util.SetPushFormat(floor,pushType, author, pushTime, content) self.index = floor self.infoSignal.emit(info) self.postSignal.emit(content) except PTT.exceptions.ConnectionClosed: self.login() except Exception as e: status = "unknown error" error_class = e.__class__.__name__ logging.warning(str(e)) break time.sleep(1) # load new posts every 1 second
def update(): global Woman global in_update in_update = True woman_temp = [] ptt_id, ptt_pw = get_pw() ptt_bot = PTT.API( # LogLevel=PTT.LogLevel.TRACE, # LogLevel=PTT.LogLevel.DEBUG, ) try: ptt_bot.login( ptt_id, ptt_pw, kick_other_login=True ) except PTT.Exceptions.LoginError: ptt_bot.log('登入失敗') return crawl_list = [ ('Beauty', PTT.data_type.post_search_type.PUSH, '50'), ] max_picture = 2000 for (board, search_type, condition) in crawl_list: try: index = ptt_bot.get_newest_index( PTT.data_type.index_type.BBS, board, search_type=search_type, search_condition=condition, ) # print(f'{board} 最新文章編號 {Index}') random_post_index = [i for i in range(index - max_picture, index + 1)] random.shuffle(random_post_index) catch_pic = 0 for index in random_post_index: # print(f'準備解析第 {IndexList.index(index) + 1} 篇 編號 {index} 已經蒐集 {Piture} 張圖片') post = ptt_bot.get_post( board, post_index=index, search_type=search_type, search_condition=condition ) if post.delete_status != PTT.data_type.post_delete_status.NOT_DELETED: continue if '[正妹]' not in post.title and '[廣告]' not in post.title: continue # print(Post.getContent()) content = post.content content = content[:content.find('--')] # print(content) all_pic_id = re.findall( r'https://(.+).jpg', content ) for album in all_pic_id: pic_url = f'https://{album}.jpg' if pic_url not in woman_temp: woman_temp.append(pic_url) catch_pic += 1 if catch_pic >= max_picture: break if catch_pic >= max_picture: break # all_pic_id = re.findall( # r'https://(.+).png', # content # ) # # for album in all_pic_id: # pic_url = f'https://{album}.png' # # if pic_url not in woman_temp: # woman_temp.append(pic_url) # catch_pic += 1 # # if catch_pic >= max_picture: # break # if catch_pic >= max_picture: # break # all_pic_id = re.findall( # r'https://(.+).gif', # content # ) # # for album in all_pic_id: # pic_url = f'https://{album}.gif' # # if pic_url not in woman_temp: # woman_temp.append(pic_url) # catch_pic += 1 # # if catch_pic >= max_picture: # break # if catch_pic >= max_picture: # break # print(f'已抓取 {catch_pic} 張圖') except Exception as e: traceback.print_tb(e.__traceback__) print(e) break # print('=' * 50) ptt_bot.logout() Woman = woman_temp in_update = False print('更新完畢')
def cheak(update, context): """Send a message when the command /cheak is issued.""" PTTBot = PTT.API() ID = config.get('PTT','ID') Password = config.get('PTT','Password') trade_info = [ ('Headphone', PTT.data_type.post_search_type.KEYWORD, '[交易]') ] try: PTTBot.login(ID, Password, kick_other_login=True) except PTT.exceptions.LoginError: PTTBot.log('登入失敗') sys.exit() except PTT.exceptions.WrongIDorPassword: PTTBot.log('帳號密碼錯誤') sys.exit() except PTT.exceptions.LoginTooOften: PTTBot.log('請稍等一下再登入') sys.exit() PTTBot.log('登入成功') update.message.reply_text('登入成功') for (trade_board, search_type, condition) in trade_info: index = PTTBot.get_newest_index( PTT.data_type.index_type.BBS, trade_board, search_type=search_type, search_condition=condition, ) print(f'{trade_board} 最新關鍵字[交易]的文章編號為 {index}') post = PTTBot.get_post( trade_board, post_index=index, search_type=search_type, search_condition=condition, ) print('標題:') print(post.title) print('作者:') print(post.author) print('內文:') print(post.content) print('=' * 50) #檢查可疑文章的作者在耳機板發了幾篇文章# post_autor = re.sub(u"\\(.*?\\)|\\{.*?}|\\[.*?]", "", post.author) print(f'{post_autor} 根據正規表示法解碼後的作者ID ') author_cheak = [ ('Headphone', PTT.data_type.post_search_type.AUTHOR, post_autor) ] for (author_board, search_type, condition) in author_cheak: index = PTTBot.get_newest_index( PTT.data_type.index_type.BBS, author_board, search_type=search_type, search_condition=condition, ) print(f'他在 {author_board} 板發了 {index} 篇文章') #查詢這篇可疑的文章# post_D_info = PTTBot.get_post( author_board, post_index = index, search_type=search_type, search_condition=condition, ) print('=' * 10 +'這是一篇可疑的文章'+ '=' * 10) print('標題:') print(post_D_info.title) print('作者:') print(post_D_info.author) print('內文:') print(post_D_info.content) print('=' * 50) if (index==1): print('這篇要被刪除的文章AID是:' + post_D_info.aid) post_D_info.author = re.sub(u"\\(.*?\\)|\\{.*?}|\\[.*?]", "", post_D_info.author) mark_type = PTT.data_type.mark_type.D PTTBot.mark_post( mark_type, 'Headphone', # AID 與 index 擇一使用 post_aid = post_D_info.aid, # Postindex 可搭配 SearchType and SearchCondition 使用 ) mark_type = PTT.data_type.mark_type.DeleteD PTTBot.mark_post( mark_type, 'Headphone', post_aid = post_D_info.aid, ) PTTBot.bucket( # 看板 'Headphone', # 幾天,請自行轉換成天數 360, # 水桶原因 '板規一、a、1,未滿三篇非交易文不得發表交易文。', # 水桶對象 post_D_info.author ) update.message.reply_text('機器人剛剛幫你水桶了一個人') update.message.reply_text('被水桶的ID是 :'+ post_D_info.author) update.message.reply_text('被水桶的AID是:'+ post_D_info.aid) update.message.reply_text('水桶的原因是:板規一、a、1,未滿三篇非交易文不得發表交易文。') else: update.message.reply_text('現在沒有人違規 開心') time.sleep(3) PTTBot.logout()
import sys import json import os import time import re import requests from io import BytesIO from configparser import ConfigParser from PyPtt import PTT from Facebooker import facebook ptt_bot = PTT.API(log_level=PTT.log.level.SILENT) fb = facebook.API() config = ConfigParser() config.read('config.ini') fb_account = config.get('facebook', 'account') fb_password = config.get('facebook', 'password') fanpage_id = config.get('facebook', 'fanpage_id') ptt_account = config.get('PTT', 'account') ptt_password = config.get('PTT', 'password') fb.login(fb_account, fb_password) try: ptt_bot.login(ptt_account, ptt_password) except PTT.exceptions.LoginError: ptt_bot.log('登入失敗') sys.exit() except PTT.exceptions.WrongIDorPassword: ptt_bot.log('帳號密碼錯誤') sys.exit() except PTT.exceptions.LoginTooOften: ptt_bot.log('請稍等一下再登入')
def test_init(): log('init', mode='w') log('===負向===') try: log('===語言 99===') PTT.API(language=99) except ValueError: log('通過') except: log('沒通過: 跳出其他例外') assert False log('===語言放字串===') try: PTT.API(language='PTT.i18n.language.ENGLISH') except TypeError: log('通過') except: log('沒通過: 跳出其他例外') assert False try: log('===亂塞 log_level===') PTT.API(log_level='log_level') log('沒通過') assert False except TypeError: log('通過') except: log('沒通過: 跳出其他例外') assert False try: log('===亂塞 log_level===') PTT.API(log_level=100) log('沒通過') assert False except ValueError: log('通過') except: log('沒通過: 跳出其他例外') assert False try: PTT.API(log_handler='test') assert False except TypeError: log('log_handler 字串測試通過') except: log('沒通過: 跳出其他例外') assert False try: PTT.API(screen_time_out='test') assert False except TypeError: log('screen_time_out 字串測試通過') except: log('沒通過: 跳出其他例外') assert False try: PTT.API(screen_long_time_out='test') assert False except TypeError: log('screen_long_time_out 字串測試通過') except: log('沒通過: 跳出其他例外') assert False try: PTT.API(host='test') assert False except TypeError: log('host 字串測試通過') except: log('沒通過: 跳出其他例外') assert False try: PTT.API(connect_mode='test') assert False except TypeError: log('host 字串測試通過') except: log('沒通過: 跳出其他例外') assert False try: PTT.API(connect_mode=PTT.connect_core.connect_mode.TELNET) assert False except ValueError: log('TELNET 測試通過') except: log('沒通過: 跳出其他例外') assert False try: PTT.API(connect_mode=PTT.connect_core.connect_mode.WEBSOCKET) log('WEBSOCKET 測試通過') except ValueError: assert False except: log('沒通過: 跳出其他例外') assert False ################################################ log('===正向===') log('===預設值===') PTT.API() log('===中文顯示===') PTT.API(language=PTT.i18n.language.CHINESE) log('===英文顯示===') PTT.API(language=PTT.i18n.language.ENGLISH) log('===log DEBUG===') PTT.API(log_level=PTT.log.level.DEBUG) log('===log INFO===') PTT.API(log_level=PTT.log.level.INFO) log('===log SLIENT===') PTT.API(log_level=PTT.log.level.SILENT) log('===log SLIENT======') PTT.API(host=PTT.data_type.host_type.LOCALHOST) ################################################ def handler(msg): with open('log.txt', 'a', encoding='utf-8') as f: f.write(msg + '\n') ptt_bot = PTT.API(log_handler=handler) ptt_bot.log('Test log') global run_ci global automation_ci global ptt_id_0 global ptt_pw_0 global ptt2_id_0 global ptt2_pw_0 global current_py_version global ptt_id_1 global ptt_pw_1 global ptt2_id_1 global ptt2_pw_1 run_ci = False automation_ci = False if '-ci' in sys.argv: run_ci = True load_from_file = False if run_ci: ptt_id_0 = os.getenv('PTT_ID_0') ptt_pw_0 = os.getenv('PTT_PW_0') ptt_id_1 = os.getenv('PTT_ID_1') ptt_pw_1 = os.getenv('PTT_PW_1') ptt2_id_0 = os.getenv('PTT2_ID_0') ptt2_pw_0 = os.getenv('PTT2_PW_0') ptt2_id_1 = os.getenv('PTT2_ID_1') ptt2_pw_1 = os.getenv('PTT2_PW_1') if ptt_id_0 is None or ptt_pw_0 is None: log('從環境變數取得帳號密碼失敗') load_from_file = True automation_ci = False else: automation_ci = True else: load_from_file = True if load_from_file: ptt_id_0, ptt_pw_0 = get_password('test_account_0.txt') ptt_id_1, ptt_pw_1 = get_password('test_account_1.txt') ptt2_id_0, ptt2_pw_0 = get_password('test_account_2.txt') ptt2_id_1, ptt2_pw_1 = get_password('test_account_3.txt') current_py_version = os.getenv('PYTHON_VERSION') if current_py_version is None: current_py_version = sys.version[:3]
with open('ptt_info.json', encoding='utf-8') as f: ptt_info = json.load(f) except FileNotFoundError: with open('ptt_info.json', 'w', encoding='utf-8') as f: sample = '''{ "ptt_id": "你的 PTT ID", "ptt_pw": "你的 PTT Password", "post_aid": "簽到文章 AID" } ''' f.write(sample) messagebox.showerror(title='25 周年簽到機器人', message='請修改 ptt_info.json 內的資訊') sys.exit() ptt_bot = PTT.API() try: ptt_bot.login(ptt_info['ptt_id'], ptt_info['ptt_pw']) except PTT.exceptions.WrongIDorPassword: messagebox.showerror(title='25 周年簽到機器人', message='帳號密碼錯誤,請確認 ptt_info.json 內的資訊') sys.exit() post_info = ptt_bot.get_post('Ptt25sign', post_aid=ptt_info['post_aid']) if not post_info or not post_info.title or not post_info.author: messagebox.showerror(title='25 周年簽到機器人', message='驗證文章 AID 失敗,請確認 ptt_info.json 內的資訊') sys.exit() # print(post_info.title) # print(post_info.author)