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")
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
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 """
#!/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 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: ' +
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)
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()
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