class BBBot: def __init__(self, config: Config): """Create a bot using the config. Required keys: bot.key, bot.running, bot.chat_id, bot.offset""" self.config = config self.running = config['bot'].getboolean('running', True) self._bot = Bot(config['bot'].get('key')) self._chat_id = config['bot'].getint('chat_id', 0) self.consume_messages() def consume_messages(self): offset = self.config['bot'].getint('offset', 0) for msg in self._bot.do('getUpdates', offset=offset, request_timeout=100): if 'channel_post' in msg and msg['channel_post']['chat']['id'] == self._chat_id \ and 'text' in msg['channel_post']: text = msg['channel_post']['text'].lower() if text in PAUSE_COMMANDS: self.running = False elif text in START_COMMANDS: self.running = True offset = msg['update_id'] self.config.set('bot', 'running', str(self.running)) self.config.set('bot', 'offset', str(offset)) self.config.persist() def send_message(self, message: str, formatting='HTML'): self._bot.send_message(self._chat_id, message, parse_mode=formatting)
def start_multimon(freq, prot, minlen, tid, rid): # replace POCSAG512 with -a POCSAG512 prot = prot.replace(" ", " -a ") # create telegram bot bot = Bot(tid) # create deque d = collections.deque(maxlen=100) # call multimon call = "rtl_fm -d0 -f " + freq + " -s 22050 | multimon-ng -t raw -a " + prot + " -f alpha -t raw /dev/stdin -" print(call) mm = subprocess.Popen(call, shell=True, stdout=subprocess.PIPE) while mm.poll() is None: # process new pocsag entry output = mm.stdout.readline().decode('utf-8') # read new line print(output) if "Alpha" not in output: # check if non alpha element continue # if yes, continue output = output.replace("<NUL>", "") # replace terminator sequence if output in d: # if the message is already in the list -> skip (pager messages might be sent multiple times) continue d.append(output) # add to deque msg = output.split("Alpha:", 1)[1] # get the message if int(len(msg)) < int(minlen): # if msg length < minlen skip continue time = strftime("%Y-%m-%d %H:%M", gmtime()) # get timestamp print(msg) # print the message try: bot.send_message(rid, 'Time: ' + time + '\nMessage: ' + msg) # send it. except: pass
class LiveTestCase(asynctest.TestCase): def setUp(self) -> None: self.api_bot = Bot(TEST_BOT_AUTH) self.user_bot = Bot(TEST_USER_AUTH) # end def async def test_send_location(self): self.user_bot.send_message()
def send(self, sender: PytgbotApiBot, receiver, reply_id) -> PytgbotApiMessage: if self.receiver: receiver = self.receiver # end if if self.reply_id is not DEFAULT_MESSAGE_ID: reply_id = self.reply_id # end if try: result = sender.send_message( receiver, self.text, parse_mode=self.parse_mode, disable_notification=self.disable_notification, reply_to_message_id=reply_id, reply_markup=self.reply_markup, disable_web_page_preview=self.disable_web_page_preview) except TgApiServerException as e: should_backoff(e) # checks if it should raise an DoRetryException raise # else it just raises as usual # end try # if result and self._next_msg: # # pass current message as reply id. # self._next_msg.reply_id == result # # end if return result
def send(self, sender: PytgbotApiBot) -> PytgbotApiMessage: try: result = sender.send_message( chat_id=self.receiver, text=self.text, parse_mode=self.parse_mode, disable_notification=self.disable_notification, reply_to_message_id=self.reply_id, reply_markup=self.reply_markup, disable_web_page_preview=self.disable_web_page_preview, allow_sending_without_reply=True, ) except TgApiServerException as e: raise # else it just raises as usual # end try # if result and self._next_msg: # # pass current message as reply id. # self._next_msg.reply_id == result # # end if return result
def send(self, sender: PytgbotApiBot, receiver, reply_id)->PytgbotApiMessage: if self.receiver: receiver = self.receiver # end if if self.reply_id is not DEFAULT_MESSAGE_ID: reply_id = self.reply_id # end if try: result = sender.send_message( receiver, self.text, parse_mode=self.parse_mode, disable_notification=self.disable_notification, reply_to_message_id=reply_id, reply_markup=self.reply_markup, disable_web_page_preview=self.disable_web_page_preview ) except TgApiServerException as e: should_backoff(e) # checks if it should raise an DoRetryException raise # else it just raises as usual # end try # if result and self._next_msg: # # pass current message as reply id. # self._next_msg.reply_id == result # # end if return result
last_update_id = -1 while True: # loop forever. for update in bot.get_updates(limit=100, offset=last_update_id+1, poll_timeout=30): last_update_id = update.update_id print("got message: {msg}".format(msg=update)) if not "message" in update: continue message = update.message if not "text" in message: continue logger.debug("got text: {msg}".format(msg=message.text.encode("utf-8"))) if not message.text == "/pics": continue origin = message.chat.id if "chat" in message else message.from_peer.id if "reply_to_message" in message: name = message.reply_to_message.from_peer.first_name peer = message.reply_to_message.from_peer.id photos = bot.get_user_profile_photos(peer).photos if len(photos) == 0: bot.send_message(origin, "No images.") continue for x in reversed(photos): biggest_image = max(x, key=lambda p: p.file_size) # get the biggest image. bot.send_photo(origin, biggest_image.file_id, caption="{name}".format(name=name, w=biggest_image.width, h=biggest_image.height) ) else: bot.send_message(origin, "Please reply to some message to select a user.") # end if # end for #end while
if i!=0: message = "Veamos tus likes desde ayer!\n\n" + message if len(fotos[iguser]['follows']) > 1: follows_diff = fotos[iguser]['follows'][-1]['count'] - fotos[iguser]['follows'][-2]['count'] else: follows_diff = 0 if len(fotos[iguser]['followed_by']) > 1: followed_diff = fotos[iguser]['followed_by'][-1]['count'] - fotos[iguser]['followed_by'][-2]['count'] else: followed_diff = 0 if followed_diff != 0 or follows_diff != 0: message = message + "Diferencia de seguidores: " + str(followed_diff) + ". Diferencia de seguidos: " + str(follows_diff) if message != "": # print('escribiendo al canal'+fotos[iguser]['telegram_id']) bot.send_message(fotos[iguser]['telegram_id'], message, parse_mode='Markdown') bot.send_message(CHAT_ID, message, parse_mode='Markdown') # print(message) try: # os.rename(dbFilePath,dbFilePath+","+str(int(time.time()))) with open(dbFilePath,'w') as dbFile: json.dump(fotos,dbFile) except: print ("There was a problem writing the dbfile. Check permissions or disk space.")
elif context['intent'] == 'roolback' and 'type' in context['parameters']: if context['parameters']['type'] == 'frontend': bot.send_message(user_id, get_doing_fallback('roolback', 'frontend')) SemacFrontend(bot, user_id).revert() elif context['parameters']['type'] == 'backend': bot.send_message(user_id, get_doing_fallback('roolback', 'backend')) SemacBackend(bot, user_id).revert() elif context['intent'] == 'view' and 'type' in context['parameters']: if context['parameters']['type'] == 'frontend': SemacFrontend(bot, user_id).show_actual_version() elif context['parameters']['type'] == 'backend': SemacBackend(bot, user_id).show_actual_version() else: bot.send_message(user_id, get_default_fallback()) # Setup bot bot = Bot(BOT_TOKEN) # Sending a message when bot is on bot.send_message(ALLOWED_IDS[0], "Estou online de novo!") # Get last message sended last_update_id = 0 while True: for update in bot.get_updates(limit=100, offset=last_update_id+1): last_update_id = update.update_id process_input(update.to_array())
if not "message" in update: continue message = update.message if not "text" in message: continue logger.debug( "got text: {msg}".format(msg=message.text.encode("utf-8"))) if not message.text == "/pics": continue origin = message.chat.id if "chat" in message else message.from_peer.id if "reply_to_message" in message: name = message.reply_to_message.from_peer.first_name peer = message.reply_to_message.from_peer.id photos = bot.get_user_profile_photos(peer).photos if len(photos) == 0: bot.send_message(origin, "No images.") continue for x in reversed(photos): biggest_image = max( x, key=lambda p: p.file_size) # get the biggest image. bot.send_photo(origin, biggest_image.file_id, caption="{name}".format(name=name, w=biggest_image.width, h=biggest_image.height)) else: bot.send_message(origin, "Please reply to some message to select a user.") # end if # end for #end while
most_viewed[videoid] = int(olddata[videoid]['viewcount'][-1]['views']) except KeyError: # print(video['snippet']['description']) olddata[videoid] = {'description' : video['snippet']['description'], 'dateposted' : video['snippet']['publishedAt'], 'viewcount': olddata[videoid]['viewcount'], 'title': video['snippet']['title'], 'thumbnail': video['snippet']['thumbnails']['high']['url']} most_viewed[videoid] = int(viewcount) #message = message + "El video '"+ title[:truncatelimit] + (title[truncatelimit:] and "...") + "' se ha visto "+ views +" veces en total, " + viewsToday + " desde ayer.\n" most_viewed_sorted = sorted(most_viewed.items(), key=itemgetter(1), reverse=True) i=0 message="" while i < 5: video=olddata[most_viewed_sorted[i][0]] #print(vid) if most_viewed_sorted[i][1] > 0: message=message + "El video '[" + video['title'][:truncatelimit] + (video['title'][truncatelimit:] and "...") + \ "](https://www.youtube.com/watch?v="+ most_viewed_sorted[i][0] + ")' fue visto " + str(most_viewed_sorted[i][1]) + \ " veces desde ayer. Tiene en total " + video['viewcount'][-1]['views'] +".\n" i+=1 if message == "": pass else: # print(message) bot.send_message(CHAT_ID, message, parse_mode='Markdown') try: with open(dbFilePath,'w') as dbFile: json.dump(olddata,dbFile) except: print ("There was a problem writing the dbfile. Check permissions or disk space.")