def main(): # Initialize telegram batch file. init_sent_db() # Connect with telegram client (first try to reuse). try: from pytg.sender import Sender telegram = Sender(host="localhost", port=4458) telegram.get_self() # required in order to force connection. except: from pytg import Telegram tg = Telegram(telegram="/opt/telegram-cli/bin/telegram-cli", pubkey_file="/opt/telegram-cli/tg-server.pub") telegram = tg.sender telegram.get_self() # required in order to force connection. # Read configuration file with different urls. with open(CONFIG) as f: content = json.load(f) # Parse file contents. for line in content: run_url(telegram,line[0],line[1],line[2],line[3])
def __init__(self, bot): self.bot = bot self.receiver = Receiver(host="localhost", port=self.bot.config.bindings_token) self.sender = Sender(host="localhost", port=self.bot.config.bindings_token) logging.getLogger("pytg").setLevel(logging.WARNING)
def main(): init(autoreset=True) bot = os.getenv('BOT', 'tensio2bot') # bot = "TensioBot" # bot = "tensio2bot" sender = Sender("127.0.0.1", 9009) res = sender.msg(bot, "/cancel") time.sleep(3) res = sender.msg(bot, "/cambiar") time.sleep(3) res = sender.msg(bot, "Sí") time.sleep(3) res = sender.msg(bot, "10:18") time.sleep(3) res = sender.history(bot, 2) comprobar(res[0], 'OK') res = sender.msg(bot, "Sí") time.sleep(3) res = sender.msg(bot, "18:29") time.sleep(5) res = sender.history(bot, 2) comprobar(res[1], 'Muy bien. Los datos han sido')
def __init__(self, bot): self.bot = bot self.receiver = Receiver(host='localhost', port=self.bot.config['bindings_token']) self.sender = Sender(host='localhost', port=self.bot.config['bindings_token']) logging.getLogger('pytg').setLevel(logging.WARNING)
def __init__(self): tgcli_port = 4458 self.setlog() if not self.start(tgcli_port): sys.exit(1) self.receiver = Receiver(host="localhost", port=tgcli_port) self.sender = Sender(host="localhost", port=tgcli_port)
class TelegramClient(object): def __init__(self, users=None, groups=None, config=None): """ List of allowed user to send messages: users List of groups to reply and receive messages: groups """ self.users = users self.groups = groups self.receiver = Receiver(port=PORT) self.sender = Sender(host=HOST, port=PORT) self.receiver.start() # extra config self.config = config or {} # start loop self.receiver.message(self.main_loop()) def _get_receiver(self, msg): # try to return message to group group_name = msg['receiver'].get('name') if group_name and group_name in self.groups: return self.groups[group_name] # try to return message to user user_name = msg['sender'].get('username') if user_name and user_name in self.users: return self.users[user_name] def send_reply(self, msg, message): self.send_message(self._get_receiver(msg), message) def send_message(self, to, message): self.sender.send_msg(to, message) def send_reply_photo(self, msg, file_path, caption=None): self.send_photo(self._get_receiver(msg), file_path, caption) def send_photo(self, to, file_path, caption=None): self.sender.send_photo(to, file_path, caption) def stop(self): self.receiver.stop() @coroutine def main_loop(self): try: while True: msg = (yield) if self.read_command(msg) == 'quit': break except Exception as e: print(u"ERROR: {}".format(e)) finally: self.stop()
def __init__(self, users=None, groups=None, config=None): """ List of allowed user to send messages: users List of groups to reply and receive messages: groups """ self.users = users self.groups = groups self.receiver = Receiver(port=PORT) self.sender = Sender(host=HOST, port=PORT) self.receiver.start() # extra config self.config = config or {} # start loop self.receiver.message(self.main_loop())
def init_tg_cli(): try: p = next( p for p in process_iter() if p.name() == 'telegram-cli' and p.cmdline()[p.cmdline().index('-P') + 1 == str(TG_CLI_PORT)]) except: print('Running telegram-cli on port {}'.format(str(TG_CLI_PORT))) p = Popen([TG_CLI_EXECUTABLE, '--json', '-d', '-P', str(TG_CLI_PORT)]) global TG_CLI_PID TG_CLI_PID = p.pid receiver = Receiver(host="localhost", port=TG_CLI_PORT) sender = Sender(host="localhost", port=TG_CLI_PORT) sender.default_answer_timeout = TG_CLI_TIMEOUT return receiver, sender
def main(): # get a Receiver instance, to get messages. receiver = Receiver(host="localhost", port=4458) # get a Sender instance, to send messages, and other querys. sender = Sender(host="localhost", port=4458) print("I am done!")
def bittrexTelegram(): initialise() balance = BittrexBot.getBalance('btc') market = input(colorama.Fore.CYAN + '[1] What Group: ' + colorama.Style.RESET_ALL) risk = input(colorama.Fore.CYAN + '[1] Risk Multiplier: ' + colorama.Style.RESET_ALL) amount = input(colorama.Fore.CYAN + '[2] % of bitcoin to spend: ' + colorama.Style.RESET_ALL) profit = input(colorama.Fore.CYAN + '[3] Profit %: ' + colorama.Style.RESET_ALL) amount, profit = percentageFix(amount, profit) amount = balance * float(amount) for i in result: if 'title' in i and market in i['title']: ExID = i['id'] log = logger.getLogger('test') log.critical('waiting') while True: print(ExID) s = Sender('127.0.0.1', 4458) messages = s.history(ExID) length = len(messages) if 'text' in messages[ length - 1] and 'https://bittrex.com/Market/Index?MarketName=BTC' in messages[ length - 1]['text']: coin = messages[length - 1]['text'].split('BTC-') st = re.sub('\\W+', '', coin[1]) BittrexBot.Trade(st, profit, amount, risk) if 'text' in messages[length - 1]: wordList = messages[length - 1]['text'].split() newWordList = [] for word in wordList: scrub = re.sub('\\W+', '', word) newWordList.append(scrub) for pair in bittrexpairs: p = pair.split('-') for word in newWordList: if word == p[1]: BittrexBot.Trade(word, profit, amount, risk) time.sleep(1)
async def _telegram(request, payload, hang): from pytg.sender import Sender sender = Sender(host="localhost", port=4458) matches = await prepare(ujson.loads(request.form['matches'][0])) porters = [porter['porter'] for porter, paths in matches] porters = await config.users.find({ 'hang': hang, 'user': { '$in': porters }, 'phone': { '$exists': True } }).to_list(None) contacts = {porter['user']: porter['phone'] for porter in porters} bag = set() for porter, (path, ) in matches: phone = contacts[porter['porter']] if phone not in bag: bag.add(phone) name = sender.contact_add(phone, phone, "")[0]['print_name'] for i, point in enumerate( path['points'][:int(len(path['points']) / 2)]): sender.send_msg(name, point['name']) sender.send_location(name, *path['points'][-i - 1]['location']) return json({'SUCCESS': True})
def main(): sender = Sender(host="localhost", port=4458) count = 0 threads = [] for i in sender.dialog_list(1000, result_timeout=999999999): if str(i.print_name) != '': try: threads.insert( count, threading.Thread(target=mark_read, args=(i.print_name, sender))) threads[count].start() except KeyboardInterrupt: break except: pass count += 1 for i in threads: i.join() print(">>> Total " + str(count + 1) + " dialogs processed.")
class Checker: def __init__(self): self.sender = Sender("127.0.0.1", 4458) def check_a_number(self, phonenumber): result = { 'phone': phonenumber, 'registered': "NULL", 'chat_id': "NULL", 'username': "******", 'check_time': "NULL", 'error_on_get': "NULL" } try: res = self.sender.contact_add(phonenumber, "check", "contact") result['check_time'] = time.ctime( ) # save the time that number checked if res == []: # not registered result['registered'] = "False" elif len(res) >= 1: # user registered on telegram print((res)) r = res[0] result['registered'] = "True" result['chat_id'] = r.peer_id if hasattr(r, 'username'): result['username'] = r.username except NoResponse: print("CLI did not responded in time") result['error_on_get'] = "No respond error" return result def check_range(self, area_code, start_range, end_range): start = start_range end = end_range + 1 for x in range(start, end): phone = area_code + str(x)[1:7] time.sleep(configs.timout_to_next) # time out result = self.check_a_number(phone) if result['error_on_get'] == "NULL": # there is no error db.save(result['phone'], result['registered'], result['chat_id'], result['username'], result['check_time']) print("the " + result['phone'] + " checked and saved to database") else: # guess telegram banned us # so sleep for a while print("Warning: it seems we are banned from telegram server!") print("wait for a moments...") time.sleep(configs.timeout_on_no_res) print("checking loop ended.")
def __init__(self, from_users=[], to_users=None): """ List of allowed user to send messages: from_users List of users that will receive the message: to_users """ self.from_users = from_users self.to_users = to_users self.receiver = Receiver(port=PORT) self.sender = Sender(host=HOST, port=PORT) self.receiver.start() # start loop self.receiver.message(self.main_loop())
def main(): """ starts dataset collector on port provided in sys.argv[1], where telegram-cli runs. """ arg_port = int(sys.argv[1]) logging.basicConfig(filename="dataset_collector.log", level=logging.INFO) receiver = Receiver(host="localhost", port=arg_port) sender = Sender(host="localhost", port=arg_port) receiver.start() receiver.message(message_rec(sender)) receiver.stop()
def main(): # get a Receiver instance, to get messages. receiver = Receiver(host="localhost", port=4458) # get a Sender instance, to send messages, and other querys. sender = Sender(host="localhost", port=4458) # start the Receiver, so we can get messages! receiver.start() # note that the Sender has no need for a start function. # add "example_function" function as message listener. You can supply arguments here (like sender). receiver.message(example_function(sender)) # now it will call the example_function and yield the new messages. # please, no more messages. (we could stop the the cli too, with sender.safe_quit() ) receiver.stop() # continues here, after exiting while loop in example_function() print("I am done!")
def main(): # get a Receiver instance, to get messages. msg_receiver = Receiver(host="localhost", port=4458) # get a Sender instance, to send messages, and other queries. msg_sender = Sender(host="localhost", port=4458) # start the Receiver, so we can get messages! msg_receiver.start( ) # note that the Sender has no need for a start function. # add "alert" function as message listener. You can supply arguments here (like sender). msg_receiver.message( alert(msg_sender) ) # now it will call the "alert" function and yield the new messages. # continues here, after exiting the while loop in example_function() # please, no more messages. (we could stop the the cli too, with sender.safe_quit() ) msg_receiver.stop() print("Shutting down app! CLI will still be running")
def startTelegram(self): self.receiver = Receiver(host="localhost",port=4458); self.sender = Sender(host="localhost",port=4458);
def __init__(self): self.sender = Sender("127.0.0.1", 4458)
# -*- coding: utf-8 -*- from __future__ import unicode_literals #from pytg.receiver import Receiver from pytg.sender import Sender import logging logging.basicConfig() #receiver = Receiver(host="localhost", port=4458) sender = Sender(host="localhost", port=4458) #receiver.start() #sender.send_msg("username_surname", "Hello") sender.send_photo("username_surname", "/home/pi/lecture/ch12/telegram/bot/gem1.png")
def main(): sender = Sender("127.0.0.1", 4458) # you need a CLI already running in json mode on port 4458. res = sender.msg("@username", "Hello!") print("Response: {response}".format(response=res))
def main(): from pytg.sender import Sender x = Sender("127.0.0.1", 4458) res = x.dialog_list() print("Got: >%s<" % res)
class bindings(object): def __init__(self, bot): self.bot = bot self.receiver = Receiver(host="localhost", port=self.bot.config.bindings_token) self.sender = Sender(host="localhost", port=self.bot.config.bindings_token) logging.getLogger("pytg").setLevel(logging.WARNING) def get_me(self): msg = self.sender.get_self() return User(msg.peer_id, msg.first_name, None, msg.username) def convert_message(self, msg): id = msg['id'] if msg.receiver.type == 'user': conversation = Conversation(msg.sender.peer_id) conversation.title = msg.sender.first_name else: if msg.receiver.type == 'channel': conversation = Conversation(-int('100' + str(msg.receiver.peer_id))) else: conversation = Conversation(-int(msg.receiver.peer_id)) conversation.title = msg.receiver.title if msg.sender.type == 'user': sender = User(int(msg.sender.peer_id)) sender.first_name = msg.sender.first_name if 'first_name' in msg.sender: sender.first_name = msg.sender.first_name if 'last_name' in msg.sender: sender.last_name = msg.sender.last_name if 'username' in msg.sender: sender.username = msg.sender.username else: if msg.sender.type == 'channel': sender = Conversation(-int('100' + str(msg.sender.peer_id))) else: sender = Conversation(-int(msg.sender.peer_id)) sender.title = msg.sender.title date = msg.date # Gets the type of the message if 'text' in msg: type = 'text' content = msg.text extra = None elif 'media' in msg: type = msg.media.type content = msg.id if 'caption' in msg.media: extra = msg.media.caption else: extra = None elif msg.event == 'service': type = 'service' if msg.action.type == 'chat_del_user': content = 'left_user' extra = msg.action.user.peer_id elif msg.action.type == 'chat_add_user': content = 'join_user' extra = msg.action.user.peer_id elif msg.action.type == 'chat_add_user_link': content = 'join_user' extra = msg.sender.peer_id else: type = None content = None extra = None else: type = None content = None extra = None # Generates another message object for the original message if the reply. if 'reply_id' in msg: reply_msg = self.sender.message_get(msg.reply_id) reply = self.convert_message(reply_msg) else: reply = None return Message(id, conversation, sender, content, type, date, reply, extra) def receiver_worker(self): try: logging.debug('Starting receiver worker...') while self.bot.started: self.receiver.start() self.receiver.message(self.main_loop()) except KeyboardInterrupt: pass def send_message(self, message): if not message.extra: message.extra = {} if message.type != 'text' and message.content.startswith('http'): message.content = download(message.content) elif message.type != 'text' and not message.content.startswith('/'): message.content = self.sender.load_file(message.content) if not message.extra or not 'caption' in message.extra: message.extra['caption'] = None if message.type == 'text': self.sender.send_typing(self.peer(message.conversation.id), 1) if 'format' in message.extra and message.extra[ 'format'] == 'Markdown': message.content = remove_markdown(message.content) elif 'format' in message.extra and message.extra[ 'format'] == 'HTML': message.content = remove_html(message.content) try: self.sender.send_msg(self.peer(message.conversation.id), message.content, enable_preview=False) except Exception as e: logging.exception(e) elif message.type == 'photo': self.sender.send_typing(self.peer(message.conversation.id), 1) # 7 try: if message.reply: self.sender.reply_photo(message.reply, message.content, message.extra['caption']) else: self.sender.send_photo(self.peer(message.conversation.id), message.content, message.extra['caption']) except Exception as e: logging.exception(e) elif message.type == 'audio': self.sender.send_typing(self.peer(message.conversation.id), 1) # 6 try: if message.reply: self.sender.reply_audio(message.reply, message.content) else: self.sender.send_audio(self.peer(message.conversation.id), message.content) except Exception as e: logging.exception(e) elif message.type == 'document': self.sender.send_typing(self.peer(message.conversation.id), 1) # 8 try: if message.reply: self.sender.reply_document(message.reply, message.content, message.extra['caption']) else: self.sender.send_document( self.peer(message.conversation.id), message.content, message.extra['caption']) except Exception as e: logging.exception(e) elif message.type == 'sticker': if message.reply: self.sender.reply_file(message.reply, message.content) else: self.sender.send_file(self.peer(message.conversation.id), message.content) elif message.type == 'video': self.sender.send_typing(self.peer(message.conversation.id), 1) # 4 try: if message.reply: self.sender.reply_video(message.reply, message.content, message.extra['caption']) else: self.sender.send_video(self.peer(message.conversation.id), message.content, message.extra['caption']) except Exception as e: logging.exception(e) elif message.type == 'voice': self.sender.send_typing(self.peer(message.conversation.id), 5) try: if message.reply: self.sender.reply_audio(message.reply, message.content) else: self.sender.send_audio(self.peer(message.conversation.id), message.content) except Exception as e: logging.exception(e) elif message.type == 'location': self.sender.send_typing(self.peer(message.conversation.id), 1) # 9 if message.reply: self.sender.reply_location(message.reply, message.content['latitude'], message.content['longitude']) else: self.sender.send_location(self.peer(message.conversation.id), message.content['latitude'], message.content['longitude']) else: print('UNKNOWN MESSAGE TYPE: ' + message.type) logging.debug("UNKNOWN MESSAGE TYPE") @coroutine def main_loop(self): while self.bot.started: msg = (yield) if (msg.event == 'message' and msg.own == False) or msg.event == 'service': message = self.convert_message(msg) self.bot.inbox.put(message) try: if message.conversation.id > 0: self.sender.mark_read(self.peer(message.sender.id)) else: self.sender.mark_read( self.peer(message.conversation.id)) except Exception as e: logging.error(e) def peer(self, chat_id): if chat_id > 0: peer = 'user#id' + str(chat_id) else: if str(chat_id)[1:].startswith('100'): peer = 'channel#id' + str(chat_id)[4:] else: peer = 'chat#id' + str(chat_id)[1:] return peer def user_id(self, username): if username.startswith('@'): command = 'resolve_username ' + username[1:] resolve = self.sender.raw(command) dict = DictObject(json.loads(resolve)) else: dict = self.sender.user_info(username) if 'peer_id' in dict: return dict.peer_id else: return False def get_id(self, user): if isinstance(user, int): return user if user.isdigit(): id = int(user) else: id = int(self.user_id(user)) return id def escape(self, string): if string is None: return None CHARS_UNESCAPED = ["\\", "\n", "\r", "\t", "\b", "\a", "'"] CHARS_ESCAPED = ["\\\\", "\\n", "\\r", "\\t", "\\b", "\\a", "\\'"] for i in range(0, 7): string = string.replace(CHARS_UNESCAPED[i], CHARS_ESCAPED[i]) return string.join(["'", "'"]) # wrap with single quotes.
def getGrayCameraImage(cam): img=cam.read()[1] gimg=cv2.cvtColor(img, cv2.COLOR_RGB2GRAY) return gimg def updateCameraImage(cam, i): i[0] = i[1] i[1] = i[2] i[2] = getGrayCameraImage(cam) # setup video capture if __name__ == "__main__": import logging logging.basicConfig() sender = Sender(host="localhost", port=4458) thresh = 32 cam = cv2.VideoCapture(0) i = [None, None, None] for n in range(3): i[n] = getGrayCameraImage(cam) while True: diff = diffImage(i) ret,thrimg=cv2.threshold(diff, thresh, 1, cv2.THRESH_BINARY) count = cv2.countNonZero(thrimg) if (count > 20): nz = np.nonzero(thrimg) cv2.rectangle(diff,(min(nz[1]),min(nz[0])),(max(nz[1]),max(nz[0])),(255,0,0),2) cv2.rectangle(i[0],(min(nz[1]),min(nz[0])),(max(nz[1]),max(nz[0])),(0,0,255),2) cv2.imwrite('detect.jpg',i[0])
def main(): x = Sender("127.0.0.1", 4458) result = x.dialog_list() print("Got: %s" % str(result))
# -*- coding: utf-8 -*- from __future__ import unicode_literals from pytg.sender import Sender sender = Sender(host="localhost", port=4458) sender.send_msg("username_surname", "Hello World!")
# print(telegram_msg) if "text" in telegram_msg: sender.msg(self._to_chat, telegram_msg['text']) elif "media" in telegram_msg: sender.fwd_media(self._to_chat, telegram_msg['id']) if telegram_msg['media']['caption']: sender.msg(self._to_chat, telegram_msg['media']['caption']) else: sender.fwd(self._to_chat, telegram_msg['id']) def __str__(self): from_info = info(self._from_chat) to_info = info(self._to_chat) # print(from_info) # print(to_info) return from_info["print_name"] + " " + to_info["print_name"] def __repr__(self): from_info = info(self._from_chat) to_info = info(self._to_chat) # print(from_info) # print(to_info) return "De " + from_info["print_name"] + " a " + to_info["print_name"] def __eq__(self, other): return self._to_chat == other._to_chat and self._from_chat == other._from_chat sender = Sender(host="localhost", port=4458) admin = sender.get_self()
default=100, help="Number of messages loaded per query") parser.add_argument('--dialogs', action='store_true', help="List all dialogs") parser.add_argument('--initdb', action='store_true', help="Initalise database") parser.add_argument('--continue', dest='continue_dump', action='store_true', help="Continue dumping after interrup") args = parser.parse_args() sender = Sender(host="localhost", port=4458) # Dialog listing if args.dialogs: for dialog in sender.dialog_list(): print(dialog.id[1:], "\t", dialog.print_name) sys.exit(0) # Check name if len(args.name) < 2: print("Invalid database name!") sys.exit(1) # Open the database conn = sqlite3.connect('%s.db' % args.name) c = conn.cursor()
class bindings(object): def __init__(self, bot): self.bot = bot self.receiver = Receiver(host="localhost", port=self.bot.config.bindings_token) self.sender = Sender(host="localhost", port=self.bot.config.bindings_token) logging.getLogger("pytg").setLevel(logging.WARNING) def get_me(self): msg = self.sender.get_self() return User(msg.peer_id, msg.first_name, None, msg.username) def convert_message(self, msg): id = msg['id'] if msg.receiver.type == 'user': conversation = Conversation(msg.sender.peer_id) conversation.title = msg.sender.first_name else: if msg.receiver.type == 'channel': conversation = Conversation(- int('100' + str(msg.receiver.peer_id))) else: conversation = Conversation(- int(msg.receiver.peer_id)) conversation.title = msg.receiver.title if msg.sender.type == 'user': sender = User(int(msg.sender.peer_id)) if 'first_name' in msg.sender: sender.first_name = msg.sender.first_name if 'last_name' in msg.sender: sender.last_name = msg.sender.last_name if 'username' in msg.sender: sender.username = msg.sender.username else: if msg.sender.type == 'channel': sender = Conversation(- int('100' + str(msg.sender.peer_id))) else: sender = Conversation(- int(msg.sender.peer_id)) sender.first_name = msg.sender.title date = msg.date # Gets the type of the message if 'text' in msg: type = 'text' content = msg.text extra = None elif 'media' in msg: type = msg.media.type content = msg.id if 'caption' in msg.media: extra = msg.media.caption else: extra = None elif msg.event == 'service': type = 'service' if msg.action.type == 'chat_del_user': content = 'left_user' extra = msg.action.user.peer_id elif msg.action.type == 'chat_add_user': content = 'join_user' extra = msg.action.user.peer_id elif msg.action.type == 'chat_add_user_link': content = 'join_user' extra = msg.sender.peer_id else: type = None content = None extra = None else: type = None content = None extra = None # Generates another message object for the original message if the reply. if 'reply_id' in msg: reply_msg = self.sender.message_get(msg.reply_id) reply = self.convert_message(reply_msg) else: reply = None return Message(id, conversation, sender, content, type, date, reply, extra) def receiver_worker(self): try: logging.debug('Starting receiver worker...') while self.bot.started: self.receiver.start() self.receiver.message(self.main_loop()) except KeyboardInterrupt: pass def send_message(self, message): if not message.extra: message.extra = {} if message.type != 'text' and message.content.startswith('http'): message.content = download(message.content) elif message.type != 'text' and not message.content.startswith('/'): message.content = self.sender.load_file(message.content) if not message.extra or not 'caption' in message.extra: message.extra['caption'] = None if message.type == 'text': self.sender.send_typing(self.peer(message.conversation.id), 1) if 'format' in message.extra and message.extra['format'] == 'Markdown': message.content = remove_markdown(message.content) elif 'format' in message.extra and message.extra['format'] == 'HTML': message.content = self.convert_links(message.content) try: if 'format' in message.extra and message.extra['format'] == 'HTML': self.sender.raw('[html] msg %s %s' % (self.peer(message.conversation.id), self.escape(message.content)), enable_preview=False) else: self.sender.send_msg(self.peer(message.conversation.id), message.content, enable_preview=False) except Exception as e: logging.exception(e) elif message.type == 'photo': self.sender.send_typing(self.peer(message.conversation.id), 1) # 7 try: if message.reply: self.sender.reply_photo(message.reply, message.content, message.extra['caption']) else: self.sender.send_photo(self.peer(message.conversation.id), message.content, message.extra['caption']) except Exception as e: logging.exception(e) elif message.type == 'audio': self.sender.send_typing(self.peer(message.conversation.id), 1) # 6 try: if message.reply: self.sender.reply_audio(message.reply, message.content) else: self.sender.send_audio(self.peer(message.conversation.id), message.content) except Exception as e: logging.exception(e) elif message.type == 'document': self.sender.send_typing(self.peer(message.conversation.id), 1) # 8 try: if message.reply: self.sender.reply_document(message.reply, message.content, message.extra['caption']) else: self.sender.send_document(self.peer(message.conversation.id), message.content, message.extra['caption']) except Exception as e: logging.exception(e) elif message.type == 'sticker': if message.reply: self.sender.reply_file(message.reply, message.content) else: self.sender.send_file(self.peer(message.conversation.id), message.content) elif message.type == 'video': self.sender.send_typing(self.peer(message.conversation.id), 1) # 4 try: if message.reply: self.sender.reply_video(message.reply, message.content, message.extra['caption']) else: self.sender.send_video(self.peer(message.conversation.id), message.content, message.extra['caption']) except Exception as e: logging.exception(e) elif message.type == 'voice': self.sender.send_typing(self.peer(message.conversation.id), 5) try: if message.reply: self.sender.reply_audio(message.reply, message.content) else: self.sender.send_audio(self.peer(message.conversation.id), message.content) except Exception as e: logging.exception(e) elif message.type == 'location': self.sender.send_typing(self.peer(message.conversation.id), 1) # 9 if message.reply: self.sender.reply_location(message.reply, message.content['latitude'], message.content['longitude']) else: self.sender.send_location(self.peer(message.conversation.id), message.content['latitude'], message.content['longitude']) else: print('UNKNOWN MESSAGE TYPE: ' + message.type) logging.debug("UNKNOWN MESSAGE TYPE") @coroutine def main_loop(self): while self.bot.started: msg = (yield) if (msg.event == 'message' and msg.own == False) or msg.event == 'service': message = self.convert_message(msg) self.bot.inbox.put(message) try: if message.conversation.id > 0: self.sender.mark_read(self.peer(message.sender.id)) else: self.sender.mark_read(self.peer(message.conversation.id)) except Exception as e: logging.error(e) def peer(self, chat_id): if chat_id > 0: peer = 'user#id' + str(chat_id) else: if str(chat_id)[1:].startswith('100'): peer = 'channel#id' + str(chat_id)[4:] else: peer = 'chat#id' + str(chat_id)[1:] return peer def user_id(self, username): if username.startswith('@'): command = 'resolve_username ' + username[1:] resolve = self.sender.raw(command) dict = DictObject(json.loads(resolve)) else: dict = self.sender.user_info(username) if 'peer_id' in dict: return dict.peer_id else: return False def get_id(self, user): if isinstance(user, int): return user if user.isdigit(): id = int(user) else: id = int(self.user_id(user)) return id def escape(self, string): if string is None: return None CHARS_UNESCAPED = ["\\", "\n", "\r", "\t", "\b", "\a", "'"] CHARS_ESCAPED = ["\\\\", "\\n", "\\r", "\\t", "\\b", "\\a", "\\'"] for i in range(0, 7): string = string.replace(CHARS_UNESCAPED[i], CHARS_ESCAPED[i]) return string.join(["'", "'"]) # wrap with single quotes. def convert_links(self, string): for link in BeautifulSoup(string, 'lxml').findAll("a"): string = string.replace(str(link), link.get("href")) return string # THESE METHODS DO DIRECT ACTIONS # def get_file(self, file_id): pass def invite_conversation_member(self, conversation_id, user_id): self.sender.chat_add_user(self.peer(conversation_id), self.peer(user_id)) def kick_conversation_member(self, conversation_id, user_id): self.sender.chat_del_user(self.peer(conversation_id), self.peer(user_id)) def unban_conversation_member(self, conversation_id, user_id): pass def conversation_info(self, conversation_id): self.api_request('sendContact', params)
# coding=utf-8 from pytg.sender import Sender from pytg.receiver import Receiver from pytg.utils import coroutine import re import time receiver = Receiver(host="localhost", port=1338) sender = Sender(host="localhost", port=1338) bot_username = '******' bot_username1 = 'WastelandWarsHelperBot' admin_username = '******' import random # Стартовать бота для корректного счетчика хилок уже с полным закупом!! medpack = 3 medx1 = 2 buffout = 2 #/ on = 1 distance1 = None distance2 = None # # ⛑Аптечка # 💌 Медпак # 💉 Мед-Х # 💊 Баффаут # 👣Пустошь # ⚔️Дать отпор # 👣Идти дальше # ⛺️Лагерь # 📟Пип-бой
class Messager(): lastcheck = 0; tg = None; sender = None receiver = None __shared_state = {} def __init__(self): self.__dict__ = self.__shared_state if (self.sender != None and self.receiver != None): print "TG is already running"; else: print "TG isn't running, start"; self.startTelegram(); def strip_non_ascii(self,string): ''' Returns the string without non ASCII characters''' stripped = (c for c in string if 0 < ord(c) < 127) return ''.join(stripped) def startTelegram(self): self.receiver = Receiver(host="localhost",port=4458); self.sender = Sender(host="localhost",port=4458); def sendToTG(self,group,msg): # print "Skip"; # if (os.path.isfile("/tmp/meetingmode")): # return # print "SendToTG"; self.sender.send_msg(unicode(group),unicode(msg)); print "Done"; def executeCommand(self,msg,channel,tguser): from Core.callbacks import Callbacks from Core.actions import Action user = User.byTguser(tguser); if (msg[0:1] == '%'): if (msg == '%whoami'): if (tguser == 'nouser'): message = Action(); message.privmsg("You don't have a TG username you donut! Read https://telegram.org/faq#q-what-are-usernames-how-do-i-get-one before you bother me again!",channel); if (channel == Config.get('gateway','ircchan1')): self.sendToTG(Config.get('gateway','tggroup1'),"You don't have a TG username you donut! Read https://telegram.org/faq#q-what-are-usernames-how-do-i-get-one before you bother me again!"); if (channel == Config.get('gateway','ircchan2')): self.sendToTG(Config.get('gateway','tggroup2'),"You don't have a TG username you donut! Read https://telegram.org/faq#q-what-are-usernames-how-do-i-get-one before you bother me again!"); if (channel == Config.get('gateway','ircchan3')): self.sendToTG(Config.get('gateway','tggroup3'),"You don't have a TG username you donut! Read https://telegram.org/faq#q-what-are-usernames-how-do-i-get-one before you bother me again!"); else: message = Action(); message.privmsg("Your TG username is "+tguser+". If you havn't already, you need to add this to the bot using .pref tguser="******""); if (channel == Config.get('gateway','ircchan1')): self.sendToTG(Config.get('gateway','tggroup1'),"Your TG username is "+tguser+". If you havn't already, you need to add this to the bot using .pref tguser="******""); if (channel == Config.get('gateway','ircchan2')): self.sendToTG(Config.get('gateway','tggroup2'),"Your TG username is "+tguser+". If you havn't already, you need to add this to the bot using .pref tguser="******""); if (channel == Config.get('gateway','ircchan3')): self.sendToTG(Config.get('gateway','tggroup3'),"Your TG username is "+tguser+". If you havn't already, you need to add this to the bot using .pref tguser="******""); elif (user is None): message = Action(); message.privmsg("You must be registered with BowBot and have your TG user set to send commands from TG",channel); if (channel == Config.get('gateway','ircchan1')): self.sendToTG(Config.get('gateway','tggroup1'),"You must be registered with BowBot and have your TG user set to send commands from TG"); if (channel == Config.get('gateway','ircchan2')): self.sendToTG(Config.get('gateway','tggroup2'),"You must be registered with BowBot and have your TG user set to send commands from TG"); if (channel == Config.get('gateway','ircchan3')): self.sendToTG(Config.get('gateway','tggroup3'),"You must be registered with BowBot and have your TG user set to send commands from TG"); else: msg = '!' + msg.lstrip("%"); line = ":"+str(user.name)+"!~"+str(user.name)+"@"+str(user.name)+".users.netgamers.org PRIVMSG "+channel+" :"+msg+""; message = Action() message.parse(line); callback = Callbacks.callback(message); def sendExternal(self,message): print "Message Command:" + message._command; if (message._command == "PART" or message._command == "QUIT" or message._command == "KICK" or message._command == "KILL"): #Do we have a group for this channel if (message._channel == Config.get('gateway','ircchan1')): if (Config.get('gateway','tggroup1') != ""): self.sendToTG(Config.get('gateway','tggroup1'),'[IRC:'+message._nick+'@'+message._channel+'] '+message._nick+' has left '+message._channel); if (message._channel == Config.get('gateway','ircchan2')): if (Config.get('gateway','tggroup2') != ""): self.sendToTG(Config.get('gateway','tggroup2'),'[IRC:'+message._nick+'@'+message._channel+'] '+message._nick+' has left '+message._channel); if (message._channel == Config.get('gateway','ircchan3')): if (Config.get('gateway','tggroup3') != ""): self.sendToTG(Config.get('gateway','tggroup3'),'[IRC:'+message._nick+'@'+message._channel+'] '+message._nick+' has left '+message._channel); if (message._command == "JOIN"): #Do we have a group for this channel if (message._channel == Config.get('gateway','ircchan1')): if (Config.get('gateway','tggroup1') != ""): self.sendToTG(Config.get('gateway','tggroup1'),'[IRC:'+message._nick+'@'+message._channel+'] '+message._nick+' has joined '+message._channel); if (message._channel == Config.get('gateway','ircchan2')): if (Config.get('gateway','tggroup2') != ""): self.sendToTG(Config.get('gateway','tggroup2'),'[IRC:'+message._nick+'@'+message._channel+'] '+message._nick+' has joined '+message._channel); if (message._channel == Config.get('gateway','ircchan3')): if (Config.get('gateway','tggroup3') != ""): self.sendToTG(Config.get('gateway','tggroup3'),'[IRC:'+message._nick+'@'+message._channel+'] '+message._nick+' has joined '+message._channel); if (message._command == "PRIVMSG" and message._msg[0:5] != '[IRC:' and message._msg[0:4] != '[WA:' and message._msg[0:4] != '[TG:' ): #Do we have a group for this channel if (message._channel == Config.get('gateway','ircchan1')): if (Config.get('gateway','tggroup1') != ""): self.sendToTG(Config.get('gateway','tggroup1'),'[IRC:'+message._nick+'@'+message._channel+'] '+message._msg+''); if (message._channel == Config.get('gateway','ircchan2')): if (Config.get('gateway','tggroup2') != ""): self.sendToTG(Config.get('gateway','tggroup2'),'[IRC:'+message._nick+'@'+message._channel+'] '+message._msg+''); if (message._channel == Config.get('gateway','ircchan3')): if (Config.get('gateway','tggroup3') != ""): self.sendToTG(Config.get('gateway','tggroup3'),'[IRC:'+message._nick+'@'+message._channel+'] '+message._msg+''); def startTGCheck(self): t = Timer(5.0,self.checkTG).start(); def checkTG(self): print "CheckTG Started"; print "Running Threads: "+str(threading.activeCount()); t = Timer(3600.0,self.checkTG).start(); #print "Stop Old Receviver"; if (self.receiver): try: self.receiver.stop(); print "Receiver stopped ok"; except: print "Unexpected error:", sys.exc_info()[0]; try: print "Start TG Checker"; self.receiver = Receiver(host="localhost",port=4458); self.receiver.start(); self.receiver.message(self.example_function(self.receiver)); self.receiver.stop(); print "TG CHeck has stopped...."; self.checkTG(); except TypeError: print "Should really figure out where these type-errors come from"; except: print sys.exc_info(); print "Unexpected error 2:", sys.exc_info()[0]; self.checkTG(); return; @coroutine def example_function(self,receiver): try: while True: print "Check"; msg = (yield) act = Action(); print('Full dump: {array}'.format(array=str( msg ))) if (msg.event == 'message'): if (hasattr(msg.sender,'username')): user = User.byTguser(msg.sender.username); if user is not None: displayUser = str(user.name); else: displayUser = str(msg.sender.name); else: displayUser = str(msg.sender.name); msg.sender.username = '******'; msg.text = self.strip_non_ascii(msg.text); if (msg.receiver and str(msg.receiver.name) == Config.get("gateway","tggroup1") and msg.text[0:5] != '[IRC:' and msg.text[0:4] != '[WA:' and msg.text[0:4] != '[TG:' ): print "Send message to " + Config.get("gateway","ircchan1"); self.actions = Action.privmsg(act,"[TG:"+displayUser+"] " + (msg.text.encode('utf_8','ignore')) , Config.get("gateway","ircchan1")) self.executeCommand(msg.text.encode('utf_8','ignore'),Config.get("gateway","ircchan1"),str(msg.sender.username)); if (msg.receiver and str(msg.receiver.name) == Config.get("gateway","tggroup2") and msg.text[0:5] != '[IRC:' and msg.text[0:4] != '[WA:' and msg.text[0:4] != '[TG:' ): print "Send message to " + Config.get("gateway","ircchan2"); self.actions = Action.privmsg(act,"[TG:"+displayUser+"] " + (msg.text.encode('utf_8','ignore')) , Config.get("gateway","ircchan2")) self.executeCommand(msg.text.encode('utf_8','ignore'),Config.get("gateway","ircchan2"),str(msg.sender.username)); if (msg.receiver and str(msg.receiver.name) == Config.get("gateway","tggroup3") and msg.text[0:5] != '[IRC:' and msg.text[0:4] != '[WA:' and msg.text[0:4] != '[TG:' ): print "Send message to " + Config.get("gateway","ircchan3"); self.actions = Action.privmsg(act,"[TG:"+displayUser+"] " + (msg.text.encode('utf_8','ignore')) , Config.get("gateway","ircchan3")) self.executeCommand(msg.text.encode('utf_8','ignore'),Config.get("gateway","ircchan3"),str(msg.sender.username)); else: print "Not A Message"; except AttributeError: print sys.exc_info(); print "Nothing we need to worry about..."; receiver.stop(); self.checkTG(); except UnicodeEncodeError: print "Characters we can't deal with!"; except KeyboardInterrupt: receiver.stop() print("Exiting")
# -*- coding: utf-8 -*- from __future__ import unicode_literals from pytg.sender import Sender from pytg.receiver import Receiver from pytg.utils import coroutine receiver = Receiver(host="localhost", port=4458) sender = Sender(host="localhost", port=4458) @coroutine def main_loop(): QUIT = False try: while not QUIT: msg = (yield) sender.status_online() if msg.event != "message" or msg.own: continue print "Message: ", msg.text if msg.text == u'hello': sender.send_msg(msg.peer.cmd, u'world') except GeneratorExit: pass else: pass receiver.start() receiver.message(main_loop()) receiver.stop
if __name__ == "__main__": parser = argparse.ArgumentParser(description='Dump telegram logs to SQLite3 database') parser.add_argument('name', type=str, nargs='?', default="", help="Database name") parser.add_argument('--id', action="store", default="", help="Channel ID (needed only with initdb!)") parser.add_argument('--step', action="store", default=100, help="Number of messages loaded per query") parser.add_argument('--dialogs', action='store_true', help="List all dialogs") parser.add_argument('--initdb', action='store_true', help="Initalise database") parser.add_argument('--continue', dest='continue_dump', action='store_true', help="Continue dumping after interrup") args = parser.parse_args() sender = Sender(host="localhost", port=4458) # Dialog listing if args.dialogs: for dialog in sender.dialog_list(): print(dialog.id[1:], "\t", dialog.print_name) sys.exit(0) # Check name if len(args.name) < 2: print("Invalid database name!") sys.exit(1)
'''Create a file with the person to send the good night''' with open('data/good_nighter.txt','r') as f: good_nighter = f.read() # User to send the good night wishes to f.close() ''' Ubuntu instructions: Do not install via snap; it won't work. Install via: sudo apt install telegram-cli ''' tg = Telegram( telegram=telegram_path, pubkey_file=pubkey_path) receiver = Receiver(host="localhost", port=4458) sender = Sender(host="localhost", port=4458) last_seen = [] last_seen.append(sender.user_info(good_nighter).when) # Dict Object: parsing via try: os.makedirs(data_dir) print("Directory " , data_dir , " Created ") except FileExistsError: print("Directory " , data_dir , " already exists. Skipping...") if not os.path.exists(dataset): with open(dataset, 'w'): pass '''Main loop for data collection''' print("Starting main loop...")
from pytg.sender import Sender from pytg.receiver import Receiver from pytg.utils import coroutine from pytg.exceptions import ConnectionError import base64 import threading import sys import psutil import os import signal # Connect to telegram print 'Connecting to telegram...' receiver = Receiver(host="localhost", port=4458) sender = Sender(host="localhost", port=4458) # Retrieve contact list contacts = {} try: counter = 0 for c in sender.dialog_list(): counter += 1 contacts[counter] = c print unicode(counter) + ': \t' + unicode(c['print_name']) except ConnectionError: print 'Could not connect to telegram-cli. Start it by issuing "telegram-cli --json -P 4458" in a separate console.' exit(1) # Ask user to choose contact
tz = pytz.timezone('Europe/Moscow') # username of bot bot_username = '******' # username for orders order_username = '******' # user_id of bot, needed for configuration bot_user_id = 'zebra1mrn' # username for reports report_user = '******' # main pytg Sender sender = Sender(host=host, port=port) # storing last 30 messages for future getting them by telegram command log_list = deque([], maxlen=30) # list for future actions action_list = deque([]) # switches bot_enabled = True corovan_enabled = True quests_enabled = False stock = False forest_enabled = False swamp_enabled = False
pubkey_path = "/home/fedebotu/tg/server.pub" '''Create a file with the person to send the good night''' with open('data/good_nighter.txt', 'r') as f: good_nighter = f.read().replace( '\n', '') # User to send the good night wishes to f.close() print('Good nighter: ', good_nighter) ''' Ubuntu instructions: Do not install via snap; it won't work. Install via: sudo apt install telegram-cli ''' tg = Telegram(telegram=telegram_path, pubkey_file=pubkey_path) receiver = Receiver(host="localhost", port=4458) sender = Sender(host="localhost", port=4458) with open('data/prediction.txt', 'r') as f: # convert to string prediction = datetime.datetime.strptime(f.read(), "%Y-%m-%d %H:%M:%S\n") f.close() print('Starting main loop...') while True: """ We read the messages and store them in an array. UTF-8 encoding is important for including emojis """ messages = [] for m in enumerate(open('data/messages.txt', 'r', encoding='utf-8')):
def main(): sender = Sender("127.0.0.1", 4458) print sender.msg("KCTFBot", u"/start") receiver = Receiver(port=4458) receiver.start() receiver.message(example_function(receiver, sender))
from pytg.sender import Sender from pytg.receiver import Receiver # get messages from pytg.exceptions import NoResponse from pytg.utils import coroutine import re import time from database import database sender = Sender("127.0.0.1", 4458) receiver = Receiver("127.0.0.1", 4458) db = database() @coroutine def checker(t,sender): quit = False try: while not quit: # loop for messages msg = (yield) # it waits until the generator has a has message here. sender.status_online() print(msg) if msg.event != "message": continue # is not a message. if msg.own: # the bot has send this message. continue # we don't want to process this message. if msg.text is None: # we have media instead. continue # and again, because we want to process only text message. phone = re.match("^[+](?=\d)\d{12}",msg.text) if phone is not None: r = t.check_number(phone.group(0)) if (r == None) or (r == False) : sender.send_msg(msg.sender.cmd, str(phone.group(0)) + " no telegram")
'dog': '🐕', 'horse': '🐎', 'goat': '🐐', 'cat': '🐈', 'pig': '🐖', 'squirrel': '🐿' } arena_cover = ['🛡головы', '🛡корпуса', '🛡ног'] arena_attack = ['🗡в голову', '🗡по корпусу', '🗡по ногам'] # поменять blue на red, black, white, yellow в зависимости от вашего замка castle = orders[castle_name] # текущий приказ на атаку/защиту, по умолчанию всегда защита, трогать не нужно current_order = {'time': 0, 'order': castle} sender = Sender( sock=socket_path) if socket_path else Sender(host=host, port=port) action_list = deque([]) log_list = deque([], maxlen=30) lt_arena = 0 get_info_diff = 360 hero_message_id = 0 last_captcha_id = 0 gold_to_left = 0 bot_enabled = True arena_enabled = True les_enabled = False peshera_enabled = True corovan_enabled = True order_enabled = True auto_def_enabled = True
class TelegramClient(object): CMD_PREFIX = 'command__' def __init__(self, from_users=[], to_users=None): """ List of allowed user to send messages: from_users List of users that will receive the message: to_users """ self.from_users = from_users self.to_users = to_users self.receiver = Receiver(port=PORT) self.sender = Sender(host=HOST, port=PORT) self.receiver.start() # start loop self.receiver.message(self.main_loop()) def command__hola(self, msg, *args): self.send_reply(msg, u'Hola!') def command__gracias(self, msg, *args): self.send_reply(msg, u'de nada!') def command__temp(self, msg, *args): humidity, temperature = Adafruit_DHT.read_retry(11, 4) if humidity is not None and temperature is not None: res = u'Temp={0:0.1f} C Humidity={1:0.1f}%'.format( temperature, humidity ) else: res = u'Failed to get reading. Try again!' self.send_reply(msg, res) def command__quit(self, msg, *args): self.send_reply(msg, u'Closing client. Good bye!') return 'quit' def send_reply(self, msg, message): to = msg['sender'].get('username') self.send_message(to, message) def send_message(self, to, message): if to in self.to_users: self.sender.send_msg(self.to_users[to], message) def is_valid(self, msg): return msg.get('sender') and msg['sender'].get('username') in self.from_users def read_command(self, msg): if self.is_valid(msg) and msg.get('text'): args = msg.get('text').split(' ') cmd = self.CMD_PREFIX + args[0].lower() if hasattr(self, cmd): return getattr(self, cmd)(*([msg]+args[1:])) return False def stop(self): self.receiver.stop() @coroutine def main_loop(self): try: while True: msg = (yield) if self.read_command(msg) == 'quit': break except Exception as e: print(u"ERROR: {}".format(e)) finally: self.stop()