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(): 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, 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(): # 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 __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)
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(2) res = sender.msg(bot, "/tension") time.sleep(2) res = sender.msg(bot, "Sí, ahora") time.sleep(2) res = sender.msg(bot, "120") time.sleep(2) res = sender.msg(bot, "90") time.sleep(2) res = sender.history(bot, 2) time.sleep(2) comprobar(res[1], 'Para confirmar que la tensión es estable') time.sleep(2) res = sender.msg(bot, "OK, ya he vuelto a tomarme la tensión") time.sleep(2) res = sender.msg(bot, "126") time.sleep(2) res = sender.msg(bot, "90") time.sleep(8) res = sender.history(bot, 2) # print("Response: {response}".format(response=res)) comprobar(res[0], 'La diferencia entre tomas es de más de') comprobar(res[1], 'Para confirmar que la tensión es estable') time.sleep(2) res = sender.msg(bot, "OK, ya he vuelto a tomarme la tensión") time.sleep(2) res = sender.msg(bot, "126") time.sleep(2) res = sender.msg(bot, "90") time.sleep(8) res = sender.history(bot, 2) comprobar(res[0], 'Muy bien') comprobar(res[1], 'Cuando quieras')
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 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 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 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)
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(): 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.")
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(2) res = sender.msg(bot, "/tension") time.sleep(2) res = sender.msg(bot, "Sí, ahora") time.sleep(2) res = sender.msg(bot, "120") time.sleep(2) res = sender.msg(bot, "90") time.sleep(2) res = sender.history(bot, 2) time.sleep(2) comprobar(res[1], 'Para confirmar que la tensión es estable') time.sleep(2) res = sender.msg(bot, "OK, ya he vuelto a tomarme la tensión") time.sleep(2) res = sender.msg(bot, "122") time.sleep(2) res = sender.msg(bot, "92") time.sleep(8) res = sender.history(bot, 2) # print("Response: {response}".format(response=res)) comprobar(res[0], 'Muy bien. Los datos han sido introducidos correctamente') comprobar(res[1], 'Cuando quieras, puedes volver a pedirme ayuda')
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")
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")
def send_telegram_notification(to, message): sender = Sender(host="localhost", port=4458) sender.send_msg(to, message)
def main(): x = Sender("127.0.0.1", 4458) result = x.dialog_list() print("Got: %s" % str(result))
def __init__(self): self.sender = Sender("127.0.0.1", 4458)
# 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 # # ⛑Аптечка # 💌 Медпак # 💉 Мед-Х # 💊 Баффаут # 👣Пустошь # ⚔️Дать отпор # 👣Идти дальше # ⛺️Лагерь # 📟Пип-бой
from core.utils import * from pytg.receiver import Receiver from pytg.sender import Sender from pytg.utils import coroutine import json tgreceiver = Receiver(host="localhost", port=config.keys.tg_cli_port) tgsender = Sender(host="localhost", port=config.keys.tg_cli_port) # Telegram-CLI bindings def peer(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(username): if username.startswith('@'): command = 'resolve_username ' + username[1:] resolve = tgsender.raw(command) dict = DictObject(json.loads(resolve)) else: dict = tgsender.user_info(username) if 'peer_id' in dict:
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))
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
def main(): from pytg.sender import Sender x = Sender("127.0.0.1", 4458) res = x.get_dialog_list() print("Got: >%s<" % res)
from time import sleep from datetime import datetime from vk_api import VkApi from config import VK_LOGIN, VK_PASSWORD from pytg.sender import Sender vk = VkApi(VK_LOGIN, VK_PASSWORD) telegram = Sender(host="localhost", port=4458) def create_welcome_message(): now_hour = datetime.timetuple(datetime.now())[3] if now_hour in range(4, 13): welcome_message = 'Доброе утро' elif now_hour in range(14, 18): welcome_message = 'Добрый день' else: welcome_message = 'Добрый вечер' return welcome_message welcome_message = create_welcome_message() def send_telegram_message(messages, user_id, user_name): telegram.send_msg( user_id, '{welcome_message}, {name}'.format(welcome_message=welcome_message, name=user_name)) telegram.send_msg(user_id, 'Я курьер TJ, меня зовут Сева.') for message in messages:
def main(): global sent, received, up, tun, encrypted, args # Process arguments parser = argparse.ArgumentParser(description='Teletun - IP over Telegram') parser.add_argument('peer_id', help='peer id (list for contact list)') parser.add_argument('-r', '--server', help='server', action='store_true') parser.add_argument('-e', '--encrypted', help='secret chat', action='store_true') parser.add_argument('-p', '--src', help='peer address', default='10.8.0.2') parser.add_argument('-s', '--dst', help='server address', default='10.8.0.1') parser.add_argument('-m', '--mask', help='mask', default='255.255.255.0') parser.add_argument('-n', '--mtu', help='MTU', default=1500) parser.add_argument('-H', '--host', help='Telegram host address', default='localhost') parser.add_argument('-P', '--port', help='Telegram port', default=4458) parser.add_argument('-a', '--auto', help='autoconfig from server', action='store_true') args = parser.parse_args() peer_id = None # Connect to telegram print('Connecting to Telegram...', file=sys.stderr) receiver = Receiver(host=args.host, port=args.port) sender = Sender(host=args.host, port=args.port) # Retrieve contact list try: contacts = [c for c in sender.dialog_list()] for i, user in enumerate(contacts): if args.peer_id == 'list': print('{:16s} {}'.format(str(user['peer_id']), str(user['print_name']))) elif str(user['peer_id']) == args.peer_id: peer_id = args.peer_id username = str(user['print_name']) if args.peer_id == 'list': sys.exit(0) except ConnectionError: print( 'Could not connect to telegram-cli. Start it by issuing "telegram-cli --json -P 4458" in a separate console.', file=sys.stderr) sys.exit(1) if peer_id is None: print('Could not find peer_id in contact list.', file=sys.stderr) sys.exit(1) print('Connecting to partner: ' + username, file=sys.stderr) # Helper function that can be executed in a thread def main_loop_starter(): receiver.start() # Start the receive loop receiver.message(main_loop()) @coroutine def main_loop(): global args, received, tun, encrypted while up: # Receive message from telegram, this includes ALL messages msg = (yield) # Check if it is an actual "message" message and if the sender is our peer if (msg is not None and msg.event == str('message') and not msg.own and str(msg.sender.peer_id) == peer_id): print('Msg: ' + msg.text, file=sys.stderr) if msg.text[0] == '-' and msg.text[1] == '-': if args.server: if msg.text == '--encrypted': print('Requested encyption for: ' + username, file=sys.stderr) try: sender.create_secret_chat(username) except Exception: pass encrypted = True elif msg.text == '--server': command_line = '--src={} --dst={} --mask={} --mtu={:d}'.format( args.src, args.dst, args.mask, args.mtu) print('Requested encyption for: ' + command_line, file=sys.stderr) print('Sending configuration:' + command_line, file=sys.stderr) sender.msg(username, str(command_line)) else: print('Receiving configuration:' + data, file=sys.stderr) args = parser.parse_args(sys.argv + data.split()) tun.down() setup_tun() tun.up() else: # Decode data and write it to the tunnel data = base64.b64decode(msg.text) received += len(data) tun.write(data) #print('Packet written', file=sys.stderr) def setup_tun(): if args.server: tun.addr = args.dst tun.dstaddr = args.src else: tun.addr = args.src + ' ' tun.dstaddr = args.dst tun.netmask = args.mask tun.mtu = args.mtu print('\tSrc: ' + tun.addr, file=sys.stderr) print('\tDst: ' + tun.dstaddr, file=sys.stderr) print('\tMask: ' + tun.netmask, file=sys.stderr) print('\tMTU: ' + str(tun.mtu), file=sys.stderr) # Create TUN device for network capture and injections tun = TunTapDevice(name='teletun') print('Device ' + tun.name + ' has been created, information follows:', file=sys.stderr) if args.server or not args.auto: # Set IP address based on --server header setup_tun() # Start TUN device tun.up() up = True print('Device ' + tun.name + ' is up.', file=sys.stderr) if not args.server and args.encrypted: print('Requesting encyption for: ' + username, file=sys.stderr) sender.msg(username, '--encrypted') time.sleep(3) # Create the receive thread via our helper method thread = threading.Thread(target=main_loop_starter) # Start the thread for receiving print('Connecting...', file=sys.stderr) thread.start() if not args.server and args.auto: print('Waiting for configuration...', file=sys.stderr) command_line = '--server' sender.msg(username, str(command_line)) while up: # Continually read from the tunnel and write data to telegram in base64 # TODO: Telegram supports str, base64 can probably be replaced for something less overhead-inducing buf = tun.read(tun.mtu) data = base64.b64encode(buf) data = ''.join(map(chr, data)) sent += len(data) if (not args.server and args.encrypted) or encrypted: sender.msg('!_' + username, data) elif not args.encrypted: sender.msg(username, data) # Cleanup and stop application up = False tun.down() receiver.stop() print('Bytes sent via Telegram: ' + str(sent), file=sys.stderr) print('Bytes received via Telegram: ' + str(received), file=sys.stderr) print('Done.', file=sys.stderr) # Literally Overkill current_process = psutil.Process() os.kill(current_process.pid, signal.SIGKILL)
'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
from pytg.sender import Sender import re, time, colorama, pickle from pytg import Telegram import BittrexBot, YobitBot, logger s = Sender('127.0.0.1', 4458) tg = Telegram(telegram='tg/bin/telegram-cli', pubkey_file='tg/tg-server.pub') receiver = tg.receiver with open('pairs.txt', 'rb') as (fp): yobitpairs = pickle.load(fp) with open('BittrexPairs.txt', 'rb') as (fp): bittrexpairs = pickle.load(fp) result = s.dialog_list() def initialise(): tg = Telegram(telegram='tg/bin/telegram-cli', pubkey_file='tg/tg-server.pub') receiver = tg.receiver sender = tg.sender count = 0 def yobitTelegram(): initialise() balance = YobitBot.getBalance('btc') market = input(colorama.Fore.CYAN + '[1] What Telegram Group: ' + colorama.Style.RESET_ALL) risk = input(colorama.Fore.CYAN + '[1] Risk Multiplier: ' +
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')):
from pytg import Telegram from pytg.sender import Sender # tg = Telegram(telegram="telegram-cli", pubkey_file="/etc/telegram-cli/server.pub") # sender = tg.sender sender = Sender('localhost', 4457) contacts = sender.dialog_list() for c in contacts: if c.get('phone'): msg = 'Happy Christmas {}!!'.format(c.get('first_name')) print('Send "{}" to {}'.format(msg, c.get('print_name'))) # sender.msg('@{}'.format(c.get('print_name')), msg) # sender.msg('@{}'.format(c.get('username')), msg) print('Done.')