Beispiel #1
0
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.")
Beispiel #2
0
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
i = input('Telegram online, please enter contact to connect to (by number): ')

if i not in contacts:
    print 'Please enter a number in the above range!'
    exit(1)

# Print username
Beispiel #3
0
def main():
    x = Sender("127.0.0.1", 4458)
    result = x.dialog_list()
    print("Got: %s" % str(result))
Beispiel #4
0
                        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()

    # Init database
    if args.initdb:
        print("Creating tables..")
Beispiel #5
0
    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)



    # Open the database
    conn = sqlite3.connect('%s.db' % args.name)
    c = conn.cursor()

    # Init database
Beispiel #6
0
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)
Beispiel #7
0
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.')
Beispiel #8
0
class PyTelegram(object):
    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 setlog(self):
        basepath = os.path.dirname(os.path.realpath(__file__))
        logdir = os.path.join(basepath, "./log")
        if not os.path.exists(logdir):
            os.mkdir(logdir)
        self.logname = os.path.join(basepath,
                                    "./log/%s.log" % time.strftime("%Y%m%d%H"))
        LOG_FORMAT = '[%(asctime)s] : %(levelname)s %(filename)s - %(funcName)s(%(lineno)d) - %(message)s'
        logging.basicConfig(
            format=LOG_FORMAT,
            level=0,
            handlers=[logging.FileHandler(self.logname, 'a', 'utf-8')])

    def need_proxy(self):
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
            s.connect(('8.8.8.8', 1))
            selfip = s.getsockname()[0]
        except Exception as e:
            logging.error(e)
            return False

        if selfip.startswith("192.168.") or selfip.startswith("10.")\
                or selfip.startswith("172.1") or selfip.startswith("10.64."):
            logging.debug("need proxy")
            return True
        else:
            logging.debug("no need proxy")
            return False

    def start(self, tgcli_port):
        try:
            s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            check = s.connect_ex(('127.0.0.1', tgcli_port))
            s.close()
        except Exception as e:
            logging.error(e)
            check = 1

        if check == 0:
            return True

        if self.need_proxy():
            cmd = """nohup proxychains telegram-cli --json --tcp-port %d >> %s 2>&1 &"""\
                % (tgcli_port, self.logname)
        else:
            cmd = """nohup telegram-cli --json --tcp-port %d >> %s 2>&1 &"""\
                % (tgcli_port, self.logname)

        logging.debug(cmd)
        ret = subprocess.Popen(cmd,
                               shell=True,
                               stderr=subprocess.PIPE,
                               stdout=subprocess.PIPE)
        ret.wait()
        logging.debug("ret wait")
        reterr = ret.stderr.read()
        logging.debug("ret err")
        retout = ret.stdout.read()
        logging.debug("ret out")
        if reterr:
            logging.error(reterr.decode("utf8"))
            return False
        logging.info(retout)
        return True

    def parse_recive(self, msg_dict):
        logging.debug(msg_dict)

    def receive_loop(self):
        @coroutine
        def receive_coroutine_loop():
            while 1:
                msg = (yield)
                self.parse_recive(msg)

        self.receiver.start()
        self.receiver.message(receive_coroutine_loop())

    def get_channel_list(self, limit=0, offset=0):
        if limit == 0 and offset == 0:
            channels = self.sender.channel_list()
        else:
            channels = self.sender.channel_list(limit, offset)
        return channels

    def get_dialog_list(self, limit=0, offset=0):
        if limit == 0 and offset == 0:
            dialogs = self.sender.dialog_list()
        else:
            dialogs = self.sender.dialog_list(limit, offset)
        return dialogs

    def channel_get_members(self, name):
        members = self.sender.channel_get_members(name)
        return members

    def chat_get_members(self, name):
        chat_info_dict = self.sender.chat_info(name)
        meminfo_list = chat_info_dict["members"]
        return meminfo_list

    def get_history(self, peer, limit=0, offset=0):
        if limit == 0:
            ret = self.sender.history(peer,
                                      retry_connect=10,
                                      result_timeout=100)
        elif offset == 0:
            ret = self.sender.history(peer, limit, retry_connect=10)
        else:
            ret = self.sender.history(peer, limit, offset, retry_connect=10)
        #logging.debug(ret)
        ret.reverse()
        history_dict = collections.OrderedDict()
        for chat_info in ret:
            try:
                if chat_info["event"] != "message":
                    continue
                chatid = chat_info["id"]
                history_dict[chatid] = chat_info
                logging.debug(chat_info)
            except Exception as e:
                logging.error(e)
        return history_dict

    def create_group(self, groupname, userlist):
        try:
            ret = self.sender.create_group_chat(groupname, userlist[0])
            logging.debug(ret)
        except Exception as e:
            logging.error(e)
            return False

        if len(userlist) == 1:
            return True

        for username in userlist[1:]:
            try:
                ret = self.sender.chat_add_user(groupname, username, 0)
                logging.debug(ret)
            except Exception as e:
                logging.error(e)
        return 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: ' +
Beispiel #10
0
def main():
	from pytg.sender import Sender
	x = Sender("127.0.0.1", 4458)
	res = x.dialog_list()
	print("Got: >%s<" % res)
Beispiel #11
0
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

try:
    contacts = [c for c in sender.dialog_list()]
    for i, user in enumerate(contacts):
        print(unicode(i) + ': \t' + unicode(user['print_name']))
except ConnectionError:
    print('Could not connect to telegram-cli. Start it by issuing "telegram-cli --json -P 4458" in a separate console.')
    sys.exit(1)

# Ask user to choose contact
i = int(input('Telegram online, please enter contact to connect to (by number): '))

# Print username
try:
    username = unicode(contacts[i]['print_name'])
    peer_id = contacts[i]['peer_id']
    print('Connecting to partner: ' + username)
except IndexError:
Beispiel #12
0
def main():
    from pytg.sender import Sender
    x = Sender("127.0.0.1", 4458)
    res = x.dialog_list()
    print("Got: >%s<" % res)
Beispiel #13
0
def main():
    x = Sender("127.0.0.1", 4458)
    result = x.dialog_list()
    print("Got: %s" % str(result))