def start_Telegram(self): # link with telegram-cli PATH_TELEGRAM = self.conf['general']['path_telegram'] PATH_PUBKEY = self.conf['general']['path_pubkey'] self.receiver = Receiver() self.receiver.start() # Thread to dump received messages self.msg_dump = MessageReceiver(self) self.msg_dump.daemon = True self.msg_dump.start() self.tg = Telegram(telegram=PATH_TELEGRAM, pubkey_file=PATH_PUBKEY) #self.receiver = self.tg.receiver self.sender = self.tg.sender
def __init__(self, tg_path = str()): if tg_path == str(): tg_path = os.path.dirname(__file__) + slash + "tg" self.tg = Telegram(telegram = tg_path + slash + "bin" + slash + "telegram-cli", pubkey_file = tg_path + slash + "tg_server.pub") self.sender = self.tg.sender self.receiver = self.tg.receiver
def init(tg_cli, pubkey_file): global tg tg = Telegram( telegram=tg_cli, pubkey_file=pubkey_file ) receiver = tg.receiver sender = tg.sender l = sender.contacts_list() return tg
def _init_telegram(self): """ Init telegram adapter with the AI's credentials for conversations. """ LOGGER.info('Connecting to Telegram servers...') self.tg = Telegram(telegram="tg/bin/telegram-cli", pubkey_file="tg/tg-server.pub", port=4460) self.receiver = self.tg.receiver self.sender = self.tg.sender self.sender.default_answer_timeout = 5.0
def download_history(telegram_binary, telegram_key, contact_name, csv_output_filename, max_messages): tg = Telegram( telegram=telegram_binary, pubkey_file=telegram_key ) sender = tg.sender print("Performing mandatory call to dialog list") sender.dialog_list() # Parameters to retrieve 1'000'000 messages chunk_message_count = 100 max_calls = int(max_messages / chunk_message_count) + 1 if max_calls == 0: raise RuntimeError("Max calls is zero.") print("We are going to attempt to retrieve " "at least " + str(max_messages) + " messages.") history = list() print("Starting to call API to retrieve history " "for contact: " + contact_name) print("This operation may take a while.") for i in range(0, max_calls): try: message_list = sender.history(contact_name, chunk_message_count, i * chunk_message_count) history.extend(message_list) # Wait a second to avoid issuing too many calls wait_time_seconds = 1 time.sleep(wait_time_seconds) except IllegalResponseException: print("Reached max offset, stopping API calls") break finally: print("Retrieved " + str(len(history)) + " messages") print("Saving history to file: " + csv_output_filename) with open(csv_output_filename, 'w', newline='') as csv_file: history_writer = csv.writer(csv_file, delimiter="\t", quotechar='"', quoting=csv.QUOTE_MINIMAL) history_writer.writerow(["date", "from", "to", "text"]) for message in history: date = message["date"] source = message["from"]["print_name"] destination = message["to"]["print_name"] text = message["text"] if "text" in message else "" history_writer.writerow([date, source, destination, text]) print("Successfully saved history to file.")
def main(): tg = Telegram( telegram= "/home/squancheveryword/telegram-bot/telegramlibsandclient/tg/bin/telegram-cli", pubkey_file= "/home/squancheveryword/telegram-bot/telegramlibsandclient/tg/tg-server.pub" ) receiver = tg.receiver sender = tg.sender receiver.start() receiver.message(lectormensajes(sender)) receiver.stop() print("FINALIZADO")
#!/usr/bin/env python3 # -*- coding: utf-8 -*- import os import sys import configparser import time from pytg import Telegram # load configuration home_dir = os.getenv("HOME") config = configparser.ConfigParser() config.read_file(open('defaults.cfg')) # get telegram tg = Telegram(telegram=home_dir + '/' + config['TELEGRAM']['APP'], pubkey_file=home_dir + '/' + config['TELEGRAM']['PUBKEY_FILE']) # load images stickers = [] try: for root, dirnames, filenames in os.walk(config['STICKERS']['PATH']): for filename in filenames: if filename.endswith(config['STICKERS']['EXTENSION']): stickers.append(os.path.join(root, filename)) except IOError: sys.exit("IO error. Aborting.") if len(stickers) == 0: sys.exit("No sticker images. Aborting.") # upload to telegram bot bot_name = config['BOT']['NAME']
send(sender, donor_cur, preview, False) time.sleep(1) sent = send(sender, donor_cur, text.id, db_forwarded) if sent: delay = random.randint(1, 3) time.sleep(delay) post_num += 1 acceptor_offset = acceptor.check_offset(acceptor_offset) donor_offset = donor.check_offset(donor_offset) if acceptor_offset == 0: rfirst = acceptor.rlist.pop(0) acceptor.rlist.append(rfirst) hfirst = acceptor.hlist.pop(0) acceptor.hlist.append(hfirst) except: pass #else: # time_inf = get_time_format() if post_num / run_off == donor.count: run_off += 1 time.sleep(arguments[4]) if __name__ == '__main__': tg = Telegram(telegram="tg/bin/telegram-cli", pubkey_file="tg/tg-server.pub", port=4558) receiver = tg.receiver sender = tg.sender main(sys.argv)
# -*- coding: utf-8 -*- import paho.mqtt.client as mqtt from pytg import Telegram import json import random import os import requests import giphypop g = giphypop.Giphy() tg = Telegram( telegram="/home/pi/tg/bin/telegram-cli", pubkey_file="/home/pi/tg/bin/tg-server.pub") receiver = tg.receiver sender = tg.sender # The callback for when the client receives a CONNACK response from the server. def on_connect(client, userdata, flags, rc): print("Connected with result code "+str(rc)) # Subscribing in on_connect() means that if we lose the connection and # reconnect then subscriptions will be renewed. client.subscribe("/opentrigger/signals/release") # The callback for when a PUBLISH message is received from the server. def on_message(client, userdata, msg): print("I GOT IT") print(msg.topic+" "+str(msg.payload)) uuid = json.loads(msg.payload)['UniqueIdentifier'] age = json.loads(msg.payload)['Age']
from pytg import Telegram from pytg.utils import coroutine import os import sys tg = Telegram(telegram="telegram-cli", pubkey_file="/work/tg/tg-server.pub") receiver = tg.receiver sender = tg.sender sender.send_msg(sys.argv[2], sys.argv[3]) res = sender.channel_list() print(res) res2 = sender.history(sys.argv[1]) print(res2)
from tools import * from threading import Timer, Thread import datetime import time from plugin import Plugin import subprocess from pytg.utils import coroutine TG_CLI_PATH = "/Users/ytl/YTL/App/telegram/bin/telegram-cli" TG_PUBKEY_FILE = "/Users/ytl/YTL/App/telegram/server.pub" global root_node root_node = None global tg tg = Telegram(telegram=TG_CLI_PATH, pubkey_file=TG_PUBKEY_FILE) global sender sender = tg.sender global receiver receiver = tg.receiver global friends friends = [] global groups groups = [] @coroutine
default=0, help='The amount of photos to send (default is 10).') parser.add_argument( '-n', '--number', type=int, default=0, help='The page number to send images from (default is 1st page)') args = parser.parse_args() telegram_path = args.tg if args.tg != '' else input( 'Enter the path to your telegram-cli installation (installation instructions: https://github.com/vysheng/tg#installation): ' ) pubkey_file_path = args.pub if args.pub != '' else input( 'Enter the path to the Telegram server public key file (for example, https://github.com/vysheng/tg/tg-server.pub): ' ) tg = Telegram(telegram=telegram_path, pubkey_file=pubkey_file_path) #sender = Sender(host="localhost", port=4458) sender = tg.sender contacts = sender.contacts_list() contactFound = False while not contactFound: recipient = args.user if args.user != '' else input( 'Enter the recepients username (replace ` ` with `_`): ') for contact in contacts: if hasattr(contact, 'username'): if contact.username == recipient: contactFound = True break else: if contact.print_name == recipient: contactFound = True
from pytg import Telegram from pytg.utils import coroutine tg = Telegram(telegram="./tg/bin/telegram-cli", pubkey_file="./tg/tg-server.pub") receiver = tg.receiver QUIT = False @coroutine def main_loop(): try: while not QUIT: msg = (yield ) # it waits until it got a message, stored now in msg. if msg.text is None: continue print(msg.event) print(msg.text) except GeneratorExit: pass except KeyboardInterrupt: pass else: pass receiver.start() receiver.message(main_loop())
def initialise(): tg = Telegram(telegram='tg/bin/telegram-cli', pubkey_file='tg/tg-server.pub') receiver = tg.receiver sender = tg.sender
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: ' +
class Telegram_ui: def __init__(self, conf): self.lock_receiver = True self.conf = conf self.boot_time = int(time.time()) # Just shortcut for some configurations : self.DATE_FORMAT = self.conf['general']['date_format'] self.NINJA_MODE = self.conf['general']['ninja_mode'] self.INLINE_IMAGE = self.conf['general']['inline_image'] self.start_Telegram() self.last_online = 1 self.online_status = {} self.read_status = {} palette = [('status_bar', self.conf['style']['status_bar_fg'], self.conf['style']['status_bar_bg']), ('date', self.conf['style']['date'], ''), ('hour', self.conf['style']['hour'], ''), ('separator', self.conf['style']['separator'], ''), ('reversed', 'standout', ''), ('cur_chan', self.conf['style']['cur_chan'], '')] # Notification if self.conf['general']['notification']: Notify.init("ncTelegram") self.image = '/usr/share/ncTelegram/t_logo.png' self.current_chan = [] self.last_media = {} # message buffer init self.msg_buffer = {} self.chan_widget = ChanWidget(self) self.print_title() self.me = self.sender.get_self() # message list self.msg_widget = MessageWidget(self) # message writing + status bar widget self.msg_send_widget = MessageSendWidget(self) # Right pannel self.right_side = urwid.Pile([self.msg_widget, (2, self.msg_send_widget)]) vert_separator = urwid.AttrMap(urwid.Filler(urwid.Columns([])), 'status_bar') # Final arrangements self.main_columns = urwid.Columns([('weight', 1, self.chan_widget), (1, vert_separator), ('weight', 5, self.right_side)]) self.main_loop = urwid.MainLoop((self.main_columns), palette, unhandled_input=self.unhandle_key, screen=urwid.raw_display.Screen()) self.main_loop.screen.set_terminal_properties(colors=256) self.lock_receiver = False self.main_loop.run() def update_online_status(self, when, status, cmd): self.online_status[cmd] = (when, status) if cmd == self.current_chan['id']: self.msg_send_widget.update_status_bar() def update_read_status(self, cmd, bool): self.read_status[cmd] = bool if cmd == self.current_chan['id']: self.msg_send_widget.update_status_bar() def display_notif(self, msg): if self.conf['general']['notification']: text = msg['text'] if msg['receiver']['type'] == 'user': sender = msg['sender']['first_name'] else: sender = msg['receiver']['name'] + ": " + msg['sender']['first_name'] Notify.Notification.new('', '<b>' + sender + '</b>\n' + text, self.image).show() def print_title(self): total_msg_waiting = sum(self.chan_widget.msg_chan.values()) if total_msg_waiting == 0: sys.stdout.write("\x1b]2;ncTelegram\x07") else: sys.stdout.write("\x1b]2;ncTelegram (" + str(total_msg_waiting) + ")\x07") def fill_msg_buffer(self, button): for chan in self.chan_widget.chans: cmd = chan['id'] if cmd not in self.msg_buffer: print_name = chan['print_name'] try: self.msg_buffer[cmd] = self.sender.history(print_name, 100) except: self.msg_buffer[cmd] = [] if self.INLINE_IMAGE: for msg in self.msg_buffer[cmd]: if 'media' in msg: image = self.msg_widget.get_inline_img(msg) self.chan_widget.update_chan_list() def is_image(self, path): return not path == None and (path.endswith('png') \ or path.endswith('jpg') \ or path.endswith('jpeg') \ or path.endswith('JPG') \ or path.endswith('PNG')) def download_media(self, msg): if 'url' in msg: return msg['url'] else: mtype = msg['media']['type'] mid = msg['id'] #file = self.sender.load_file(mid) if mtype == 'photo': file = self.sender.load_photo(mid) elif mtype == 'document': file = self.sender.load_document(mid) else: file = None return file def open_file(self, path): if self.conf['general']['open_file'] and path != None: subprocess.Popen(['xdg-open', path], stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL) def start_Telegram(self): # link with telegram-cli PATH_TELEGRAM = self.conf['general']['path_telegram'] PATH_PUBKEY = self.conf['general']['path_pubkey'] self.receiver = Receiver() self.receiver.start() # Thread to dump received messages self.msg_dump = MessageReceiver(self) self.msg_dump.daemon = True self.msg_dump.start() self.tg = Telegram(telegram=PATH_TELEGRAM, pubkey_file=PATH_PUBKEY) #self.receiver = self.tg.receiver self.sender = self.tg.sender def stop_Telegram(self): self.sender.status_offline() #self.tg.stopCLI() # Because of a bug in pytg, this is stopCLI without the line "self._proc.communicate('quit\n')" self.sender.terminate() # not let the cli end close first -> avoid bind: port already in use. self.receiver.stop() self.sender.safe_quit() if self.tg._check_stopped(): return None self.sender.quit() if self.tg._check_stopped(): return None self.sender.stop() # quit and safe quit are done, we don't need the sender any longer. if self.tg._check_stopped(): return None if self.tg._check_stopped(): return None self.tg._proc.terminate() if self.tg._check_stopped(): return None self.tg._proc.kill() if self.tg._check_stopped(): return None self.tg._proc.wait() self.tg._check_stopped() def exit(self): if self.conf['general']['notification']: Notify.uninit() sys.stdout.write("\x1b]2;\x07") self.stop_Telegram() raise urwid.ExitMainLoop def unhandle_key(self, key): if key == self.conf['keymap']['quit']: self.exit() elif key == 'esc': self.msg_widget.draw_separator() elif key == self.conf['keymap']['prev_chan']: self.chan_widget.go_prev_chan() elif key == self.conf['keymap']['next_chan']: self.chan_widget.go_next_chan() elif key == self.conf['keymap']['open_file'] and \ self.last_media != {} and \ self.conf['general']['open_file']: path = self.download_media(self.last_media) self.open_file(path) elif key == self.conf['keymap']['insert_text']: self.main_columns.focus_position = 2 self.right_side.focus_position = 1 elif key == "'": self.main_columns.focus_position = 2 self.right_side.focus_position = 1 self.msg_send_widget.widgetEdit.insert_text("'")
class Telegram_ui: def __init__(self, conf): self.lock_receiver = True self.conf = conf self.boot_time = int(time.time()) # Just shortcut for some configurations : self.DATE_FORMAT = self.conf['general']['date_format'] self.NINJA_MODE = self.conf['general']['ninja_mode'] self.INLINE_IMAGE = self.conf['general']['inline_image'] self.start_Telegram() self.last_online = 1 self.online_status = {} self.read_status = {} palette = [('status_bar', self.conf['style']['status_bar_fg'], self.conf['style']['status_bar_bg']), ('date', self.conf['style']['date'], ''), ('hour', self.conf['style']['hour'], ''), ('separator', self.conf['style']['separator'], ''), ('reversed', 'standout', ''), ('cur_chan', self.conf['style']['cur_chan'], '')] # Notification if self.conf['general']['notification']: Notify.init("ncTelegram") self.image = '/usr/share/ncTelegram/t_logo.png' self.current_chan = [] self.last_media = {} # message buffer init self.msg_buffer = {} self.chan_widget = ChanWidget(self) self.print_title() self.me = self.sender.get_self() # message list self.msg_widget = MessageWidget(self) # message writing + status bar widget self.msg_send_widget = MessageSendWidget(self) # Right pannel self.right_side = urwid.Pile( [self.msg_widget, (2, self.msg_send_widget)]) vert_separator = urwid.AttrMap(urwid.Filler(urwid.Columns([])), 'status_bar') # Final arrangements self.main_columns = urwid.Columns([('weight', 1, self.chan_widget), (1, vert_separator), ('weight', 5, self.right_side)]) self.main_loop = urwid.MainLoop((self.main_columns), palette, unhandled_input=self.unhandle_key, screen=urwid.raw_display.Screen()) self.main_loop.screen.set_terminal_properties(colors=256) self.lock_receiver = False self.main_loop.run() def update_online_status(self, when, status, cmd): self.online_status[cmd] = (when, status) if cmd == self.current_chan['id']: self.msg_send_widget.update_status_bar() def update_read_status(self, cmd, bool): self.read_status[cmd] = bool if cmd == self.current_chan['id']: self.msg_send_widget.update_status_bar() def display_notif(self, msg): if self.conf['general']['notification']: text = msg['text'] if msg['receiver']['type'] == 'user': sender = msg['sender']['first_name'] else: sender = msg['receiver']['name'] + ": " + msg['sender'][ 'first_name'] Notify.Notification.new('', '<b>' + sender + '</b>\n' + text, self.image).show() def print_title(self): total_msg_waiting = sum(self.chan_widget.msg_chan.values()) if total_msg_waiting == 0: sys.stdout.write("\x1b]2;ncTelegram\x07") else: sys.stdout.write("\x1b]2;ncTelegram (" + str(total_msg_waiting) + ")\x07") def fill_msg_buffer(self, button): for chan in self.chan_widget.chans: cmd = chan['id'] if cmd not in self.msg_buffer: print_name = chan['print_name'] try: self.msg_buffer[cmd] = self.sender.history(print_name, 100) except: self.msg_buffer[cmd] = [] if self.INLINE_IMAGE: for msg in self.msg_buffer[cmd]: if 'media' in msg: image = self.msg_widget.get_inline_img(msg) self.chan_widget.update_chan_list() def is_image(self, path): return not path == None and (path.endswith('png') \ or path.endswith('jpg') \ or path.endswith('jpeg') \ or path.endswith('JPG') \ or path.endswith('PNG')) def download_media(self, msg): if 'url' in msg: return msg['url'] else: mtype = msg['media']['type'] mid = msg['id'] #file = self.sender.load_file(mid) if mtype == 'photo': file = self.sender.load_photo(mid) elif mtype == 'document': file = self.sender.load_document(mid) else: file = None return file def open_file(self, path): if self.conf['general']['open_file'] and path != None: subprocess.Popen(['xdg-open', path], stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL) def start_Telegram(self): # link with telegram-cli PATH_TELEGRAM = self.conf['general']['path_telegram'] PATH_PUBKEY = self.conf['general']['path_pubkey'] self.receiver = Receiver() self.receiver.start() # Thread to dump received messages self.msg_dump = MessageReceiver(self) self.msg_dump.daemon = True self.msg_dump.start() self.tg = Telegram(telegram=PATH_TELEGRAM, pubkey_file=PATH_PUBKEY) #self.receiver = self.tg.receiver self.sender = self.tg.sender def stop_Telegram(self): self.sender.status_offline() #self.tg.stopCLI() # Because of a bug in pytg, this is stopCLI without the line "self._proc.communicate('quit\n')" self.sender.terminate( ) # not let the cli end close first -> avoid bind: port already in use. self.receiver.stop() self.sender.safe_quit() if self.tg._check_stopped(): return None self.sender.quit() if self.tg._check_stopped(): return None self.sender.stop( ) # quit and safe quit are done, we don't need the sender any longer. if self.tg._check_stopped(): return None if self.tg._check_stopped(): return None self.tg._proc.terminate() if self.tg._check_stopped(): return None self.tg._proc.kill() if self.tg._check_stopped(): return None self.tg._proc.wait() self.tg._check_stopped() def exit(self): if self.conf['general']['notification']: Notify.uninit() sys.stdout.write("\x1b]2;\x07") self.stop_Telegram() raise urwid.ExitMainLoop def unhandle_key(self, key): if key == self.conf['keymap']['quit']: self.exit() elif key == 'esc': self.msg_widget.draw_separator() elif key == self.conf['keymap']['prev_chan']: self.chan_widget.go_prev_chan() elif key == self.conf['keymap']['next_chan']: self.chan_widget.go_next_chan() elif key == self.conf['keymap']['open_file'] and \ self.last_media != {} and \ self.conf['general']['open_file']: path = self.download_media(self.last_media) self.open_file(path) elif key == self.conf['keymap']['insert_text']: self.main_columns.focus_position = 2 self.right_side.focus_position = 1 elif key == "'": self.main_columns.focus_position = 2 self.right_side.focus_position = 1 self.msg_send_widget.widgetEdit.insert_text("'")
advance_time = 30 # Minutes we send the message in advance with respect to the prediction for being more confident # the receiver will get the goodnight promptly telegram_path = "/usr/bin/telegram-cli" 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 """
import socketserver import asyncio import functools import logging from concurrent.futures import ThreadPoolExecutor from pytg import Telegram, IllegalResponseException from pytg.utils import coroutine from irc.server import IRCClient logging.basicConfig(level=logging.ERROR) CONTROL_CHANNELS = ["#telegram"] TGM = Telegram(telegram="/usr/bin/telegram-cli", pubkey_file="/etc/telegram/TG-server.pub") class IRCChannel(object): """ IRC Channel handler. """ # pylint: disable=too-few-public-methods def __init__(self, name, topic='Telegram channel'): self.name = name self.topic_by = 'Telegram' self.topic = topic self.clients = set()