Git Product home page Git Product logo

pytg's Introduction

PyTg

Version 0.4.10

Join pytg_group group on telegram get it from PyPI PyPI

A Python package that communicates with the Telegram messenger CLI, to send and receive messages and more. Since January 2014

Telegram is an Whatsapp like Instant messenger, with clients for virtually every device you use.

Works with Python 2.7 and 3

I really recommend to use Python 3, because of it's build in unicode support. Python 2 uses ascii only bytestrings, causing much, much trouble when dealing with characters like öäüß or emojis. (Trust me, I've been there)
~ luckydonald

Alternative: BotApi

If you'd like to use the Telegram Bot Api instead, there also is pytgbot. It features a complete object oriented approach, mapping all the possible server responses. So you always know what attributes to expect.

Content

Install

Dependencies

  • Install the Telegram CLI (from @vysheng), follow the official Instructions
  • Install up to date fork of Telegram CLI (by @kenorb-contrib), follow the Instructions there.

Pytg

Install form PyPI on PyPI
pip install pytg

To upgrade append the --upgrade flag.

Install from source

(Beta versions are in the development branch)

  • a) Get the latest pytg code from github.
    git clone https://github.com/luckydonald/pytg.git && cd pytg
  • b) To update already existing code, navigate to the root inside the pytg folder, then git pull
  • Install sudo python setup.py install
    • The dependency "DictObject" should be installed automatically by this. If not, it is available on PyPI:
      sudo pip install DictObject
    • Same goes for "luckydonaldUtils":
      sudo pip install luckydonald-utils

Done.

Usage

Note: The examples files produce syntax errors for python 3.0 - 3.2, the pytg package itself is not affacted by this!
To fix, just remove the u in front of the strings: change u"foobar" to "foobar (see issue #39 and Python 3.3 accepts u'unicode' syntax again).

Start telegram

Create a Telegram Instance. This will manage the CLI process, and registers the Sender and Receiver for you.

from pytg import Telegram
tg = Telegram(
	telegram="/path/to/tg/bin/telegram-cli",
	pubkey_file="/path/to/tg/tg-server.pub")
receiver = tg.receiver
sender = tg.sender

If you don't want pytg to start the cli for you, start it yourself with --json -P 4458 (port 4458). You can then use the Receiver and/or the Sender like this:

from pytg.sender import Sender
from pytg.receiver import Receiver
receiver = Receiver(host="localhost", port=4458)
sender = Sender(host="localhost", port=4458)

Send a message

sender.send_msg("username", "Hello World!")
# Easy huh?

Receiving messages

You need a function as main loop.

@coroutine # from pytg.utils import coroutine
def main_loop():
	while not QUIT:
		msg = (yield) # it waits until it got a message, stored now in msg.
		print("Message: ", msg.text)
		# do more stuff here!
	#
#

Last step is to register that function:

# start the Receiver, so we can get messages!
receiver.start()

# let "main_loop" get new message events.
# You can supply arguments here, like main_loop(foo, bar).
receiver.message(main_loop())
# now it will call the main_loop function and yield the new messages.

That's the basics. Have a look into the examples folder. For starters, I recommend:

  • dump.py - is usefull to see, how the messages look like.
  • ping.py - is usefull to see how to interact with pytg, send messages etc.

More Documentation

The Sender object features a rich build-in help, inside the python interpreter type:

from pytg.sender import Sender
help(Sender)  # list all commands
help(Sender.get_self)  # get help for a specific command

This is also availabe as generated documentation here on github. Also have a look at the Changelog to see what's going on.

To generate the documentation yourself:

from pytg.sender import create_automatic_documentation; create_automatic_documentation()

You can also have a look at the old documentation

Contribute

You can help!

Note: There is a version in the making, supporting the cli via socket (as before), the CLI via its build in python (aka. tgl) and brand new, the Telegram bot api as well. Receiving messages is already possible with all three (even simultaneously). Also it features neat classes for everything. Currently I lack the time to continue that.
See the develop branch for that. Maybe you can help make that happen.

In case of errors

First you should set logging to level DEBUG to see what's going on.

# add this to the first lines in your file
import logging
logging.basicConfig(level=logging.DEBUG)

If you are about to open a new issue, search the existing ones (open and closed) first. Sometimes they are already reported or even solved.

Examples

There are some example scripts in the examples folder:

  • command_send_message: Simplest way to just send a message.

  • command_who_am_i: A simple example printing infos about yourself

    • get the @username etc.
  • command_dialog_list: Simpler example printing the list of chats you have.

    • Shows how to execute commands like dialog_list on the CLI.
  • bot_dump: A small bot printing the msg message object.

    • So you can see yourself how messages look like.
  • bot_ping: A simple bot reacting to messages.

    • like the dump bot, but it responds to a ping with a pong.
  • bot_source_of_reply: When replying to any message with #top, the bot will show you the origin of that reply.

    • This demonstrates how you could use message_get command and the reply_id information.
  • bot_with_context: Talk to a bot, not only a simple command.

    • Demonstrates how to build converations with the use of generators and the yield statement.

URL Changes

If you started with pytg after 2015, you can ignore this. If you cloned from luckydonald/pytg, you can ignore this. Here is how to update your local git clone to this url when your old one was set to https://github.com/efaisal/pytg.git` (before I started maintaining it in September 2014)

# navigate into the clone
cd pytg	 # not pytg/pytg!
# change to the new url
git remote set-url origin https://github.com/luckydonald/pytg.git
# download the changes
git pull
# don't forget to install the newest official cli: https://github.com/vysheng/tg

If that failes at some point, just Install it from scratch.

Thanks!

pytg's People

Contributors

belegnar avatar efaisal avatar huiyiqun avatar ibaklanov avatar juanpotato avatar juanprq avatar justingood avatar kaxap avatar luckydonald avatar nekmo avatar spikeekips avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pytg's Issues

telegram not running

If I try one of the examples (dump.py / pingbot.py), I get this error message:
Traceback (most recent call last):
File "pingbot.py", line 66, in
tg.poll()
File "/usr/local/lib/python2.7/dist-packages/pytg/init.py", line 38, in poll
raise TelegramError('telegram not running')
pytg.TelegramError: telegram not running

Telegram is installed and is working. What am I doing wrong?

Unable to run with python3

I am trying to use pytg with Python v3.2.3 on a Raspberry Pi (latest model, latest Raspbian), but I'm getting multiple SyntaxError: invalid syntax. Am I missing something really obvious? If your project is compatible with python3, then why is it complaining about python2.7-style lines of code?

The telegram-cli is installed and works great, just typing commands via its command line. For using it with pytg, I am running it as specified in your documentation: bin/telegram-cli --json -P 4458

What works:

  • After git clone for pytg, running python setup.py install works fine
  • Running python pytg/examples/ping.py works great (Python 2.7.3)

What does not:

  • After git clone for pytg, running python3 setup.py install shows
Traceback (most recent call last):
  File "setup.py", line 8, in <module>
    from pytg import VERSION
  File "/home/pi/pytg/pytg/__init__.py", line 9, in <module>
    from .encoding import to_unicode as u
  File "/home/pi/pytg/pytg/encoding.py", line 36
    return u"\\"
               ^
SyntaxError: invalid syntax
  • Running python3 pytg/examples/ping.py shows
  File "pytg/examples/ping.py", line 57
    if msg.text == u"ping":
                         ^
SyntaxError: invalid syntax

can't start ./telegram

Hi,
just installed your version, but I get an error trying to start it up. Here's the log:

~ $ git clone https://github.com/efaisal/tg.git && cd tg
Cloning into 'tg'...
remote: Counting objects: 1351, done.
remote: Compressing objects:   0% (1/425)   
remote: Compressing objects:   1% (5/425)   
[...]
remote: Compressing objects: 100% (425/425)   
remote: Compressing objects: 100% (425/425), done.
Receiving objects:   0% (1/1351)   
Receiving objects:   1% (14/1351)   
[...]  
Receiving objects:  98% (1324/1351), 484.00 KiB | 474 KiB/s   
Receiving objects:  99% (1338/1351), 484.00 KiB | 474 KiB/s   
remote: Total 1351 (delta 921), reused 1351 (delta 921)
Receiving objects: 100% (1351/1351), 484.00 KiB | 474 KiB/s   
Receiving objects: 100% (1351/1351), 656.05 KiB | 474 KiB/s, done.
Resolving deltas:   0% (0/921)   
Resolving deltas:   6% (63/921)   
[...]   
Resolving deltas:  99% (912/921)   
Resolving deltas: 100% (921/921)   
Resolving deltas: 100% (921/921), done.

~/tg $ ./configure 
checking for gcc... gcc
checking whether the C compiler works... yes
checking for C compiler default output file name... a.out
checking for suffix of executables... 
checking whether we are cross compiling... no
checking for suffix of object files... o
checking whether we are using the GNU C compiler... yes
checking whether gcc accepts -g... yes
checking for gcc option to accept ISO C89... none needed
checking for sqrt in -lm... yes
checking for library containing clock_gettime... -lrt
checking for library containing backtrace... none required
checking for inflate in -lz... yes
checking for AES_set_encrypt_key in -lcrypto... yes
checking for rl_save_prompt in -lreadline... yes
checking for libconfig... enabled
checking for config_init in -lconfig... yes
checking for liblua... checking how to run the C preprocessor... gcc -E
checking for grep that handles long lines and -e... /bin/grep
checking for egrep... /bin/grep -E
checking for ANSI C header files... yes
checking for sys/types.h... yes
checking for sys/stat.h... yes
checking for stdlib.h... yes
checking for string.h... yes
checking for memory.h... yes
checking for strings.h... yes
checking for inttypes.h... yes
checking for stdint.h... yes
checking for unistd.h... yes
enabled
checking for lua... /usr/bin/lua
checking if /usr/bin/lua is a Lua interpreter... yes
checking for lua version... 5.2
checking for lua platform... unknown
checking for lua script directory... ${prefix}/share/lua/5.2
checking for lua module directory... ${exec_prefix}/lib/lua/5.2
checking if LUA_VERSION is defined... yes
checking lua.h usability... no
checking lua.h presence... no
checking for lua.h... no
checking lualib.h usability... no
checking lualib.h presence... no
checking for lualib.h... no
checking lauxlib.h usability... no
checking lauxlib.h presence... no
checking for lauxlib.h... no
checking luaconf.h usability... no
checking luaconf.h presence... no
checking for luaconf.h... no
checking for Lua headers in... /usr/include/lua5.2
checking lua.h usability... yes
checking lua.h presence... yes
checking for lua.h... yes
checking lualib.h usability... yes
checking lualib.h presence... yes
checking for lualib.h... yes
checking lauxlib.h usability... yes
checking lauxlib.h presence... yes
checking for lauxlib.h... yes
checking luaconf.h usability... yes
checking luaconf.h presence... yes
checking for luaconf.h... yes
checking for Lua header version... 5.2
checking if Lua header version matches 5.2... yes
checking if LUA_VERSION is defined... yes
checking for library containing exp... none required
checking for library containing dlopen... none required
checking for library containing lua_load... -llua5.2
checking execinfo.h usability... yes
checking execinfo.h presence... yes
checking for execinfo.h... yes
checking fcntl.h usability... yes
checking fcntl.h presence... yes
checking for fcntl.h... yes
checking malloc.h usability... yes
checking malloc.h presence... yes
checking for malloc.h... yes
checking netdb.h usability... yes
checking netdb.h presence... yes
checking for netdb.h... yes
checking for stdlib.h... (cached) yes
checking for string.h... (cached) yes
checking for unistd.h... (cached) yes
checking arpa/inet.h usability... yes
checking arpa/inet.h presence... yes
checking for arpa/inet.h... yes
checking mach/mach.h usability... no
checking mach/mach.h presence... no
checking for mach/mach.h... no
checking netinet/in.h usability... yes
checking netinet/in.h presence... yes
checking for netinet/in.h... yes
checking sys/file.h usability... yes
checking sys/file.h presence... yes
checking for sys/file.h... yes
checking sys/socket.h usability... yes
checking sys/socket.h presence... yes
checking for sys/socket.h... yes
checking termios.h usability... yes
checking termios.h presence... yes
checking for termios.h... yes
checking for size_t... yes
checking for uid_t in sys/types.h... yes
checking for inline... inline
checking for stdlib.h... (cached) yes
checking for GNU libc compatible malloc... yes
checking for stdlib.h... (cached) yes
checking for GNU libc compatible realloc... yes
checking for alarm... yes
checking for endpwent... yes
checking for memset... yes
checking for memmove... yes
checking for mkdir... yes
checking for select... yes
checking for socket... yes
checking for strdup... yes
checking for strndup... yes
checking for uname... yes
configure: creating ./config.status
config.status: creating Makefile
config.status: creating config.h
config.status: config.h is unchanged

~/tg $ make
gcc -g -O2 -I/usr/include/lua5.2  -DHAVE_CONFIG_H -Wall -Wextra -Werror -Wno-deprecated -fno-strict-aliasing -fno-omit-frame-pointer -ggdb -I. -I. -c main.c -o main.o
gcc -g -O2 -I/usr/include/lua5.2  -DHAVE_CONFIG_H -Wall -Wextra -Werror -Wno-deprecated -fno-strict-aliasing -fno-omit-frame-pointer -ggdb -I. -I. -c loop.c -o loop.o
gcc -g -O2 -I/usr/include/lua5.2  -DHAVE_CONFIG_H -Wall -Wextra -Werror -Wno-deprecated -fno-strict-aliasing -fno-omit-frame-pointer -ggdb -I. -I. -c interface.c -o interface.o
gcc -g -O2 -I/usr/include/lua5.2  -DHAVE_CONFIG_H -Wall -Wextra -Werror -Wno-deprecated -fno-strict-aliasing -fno-omit-frame-pointer -ggdb -I. -I. -c net.c -o net.o
gcc -g -O2 -I/usr/include/lua5.2  -DHAVE_CONFIG_H -Wall -Wextra -Werror -Wno-deprecated -fno-strict-aliasing -fno-omit-frame-pointer -ggdb -I. -I. -c mtproto-common.c -o mtproto-common.o
gcc -g -O2 -I/usr/include/lua5.2  -DHAVE_CONFIG_H -Wall -Wextra -Werror -Wno-deprecated -fno-strict-aliasing -fno-omit-frame-pointer -ggdb -I. -I. -c mtproto-client.c -o mtproto-client.o
gcc -g -O2 -I/usr/include/lua5.2  -DHAVE_CONFIG_H -Wall -Wextra -Werror -Wno-deprecated -fno-strict-aliasing -fno-omit-frame-pointer -ggdb -I. -I. -c queries.c -o queries.o
gcc -g -O2 -I/usr/include/lua5.2  -DHAVE_CONFIG_H -Wall -Wextra -Werror -Wno-deprecated -fno-strict-aliasing -fno-omit-frame-pointer -ggdb -I. -I. -c structures.c -o structures.o
gcc -g -O2 -I/usr/include/lua5.2  -DHAVE_CONFIG_H -Wall -Wextra -Werror -Wno-deprecated -fno-strict-aliasing -fno-omit-frame-pointer -ggdb -I. -I. -c binlog.c -o binlog.o
gcc -g -O2 -I/usr/include/lua5.2  -DHAVE_CONFIG_H -Wall -Wextra -Werror -Wno-deprecated -fno-strict-aliasing -fno-omit-frame-pointer -ggdb -I. -I. -c tools.c -o tools.o
gcc -g -O2 -I/usr/include/lua5.2  -DHAVE_CONFIG_H -Wall -Wextra -Werror -Wno-deprecated -fno-strict-aliasing -fno-omit-frame-pointer -ggdb -I. -I. -c lua-tg.c -o lua-tg.o
gcc main.o loop.o interface.o net.o mtproto-common.o mtproto-client.o queries.o structures.o binlog.o tools.o lua-tg.o  -rdynamic -ggdb -lssl -lcrypto -lz -lrt -lm   -lreadline -lconfig -llua5.2  -o telegram
~/tg $ ./telegram 
Telegram-client version 0.01-beta, Copyright (C) 2013 Vitaly Valtman
Telegram-client comes with ABSOLUTELY NO WARRANTY; for details type `show_license'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show_license' for details.
telegram: queries.c:349: help_get_config_on_answer: Assertion `fetch_int () == 0x232d5905' failed.
SIGABRT received

int as argument for Sender's functions doesn't work.

int as argument does not work.
Fails concatenating the final command string arg_string = " ".join([u(x) for x in args])

s.history('user_name', 10)
# log/stacktrace shows:
DEBUG:pytg.sender:Parsing history: Argument user_name - <user> (needed)
DEBUG:pytg.sender:Parsing history: Argument 10 - [limit] (needed)
DEBUG:pytg.sender:Skipping missing optional parameter #2 [offset] (type NonNegativeNumber) in function history.
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/path/to/pytg/pytg/sender.py", line 548, in command_alias
    return self.execute_function(command_name, *args, **kwargs)
  File "/path/to/pytg/pytg/sender.py", line 252, in execute_function
    result = self._do_command(command_name, new_args, answer_timeout=self.default_answer_timeout, retry_connect=retry_connect, enable_preview=enable_preview, reply_id=reply_id)
  File "/path/to/pytg/pytg/sender.py", line 356, in _do_command
    arg_string = " ".join([u(x) for x in args])
TypeError: sequence item 1: expected str instance, int found
>>> from pytg.sender import Sender ; import logging
>>> s.execute_function('history', 'user_name', 10)
DEBUG:pytg.sender:Parsing history: Argument user_name - <user> (needed)
DEBUG:pytg.sender:Parsing history: Argument 10 - [limit] (needed)
DEBUG:pytg.sender:Skipping missing optional parameter #2 [offset] (type NonNegativeNumber) in function history.
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/path/to/pytg/pytg/sender.py", line 252, in execute_function
    result = self._do_command(command_name, new_args, answer_timeout=self.default_answer_timeout, retry_connect=retry_connect, enable_preview=enable_preview, reply_id=reply_id)
  File "/path/to/pytg/pytg/sender.py", line 356, in _do_command
    arg_string = " ".join([u(x) for x in args])
TypeError: sequence item 1: expected str instance, int found```

Get sticker data?

Original Title: How to get raw message data in receiver?

I need to parse stickers in messages for my bot, but pytg instead of sticker info show me only that media is document u'media': {u'type': u'document'} without sticker id, sticker link etc...

channel_info command has no channel_description in results

Description part of channel_info is missed in results.
For example in telegram-cli:

> channel_info @elyas_hazrati
Channel [broadcast] کانال الیاس حضرتی @elyas_hazrati (#1002126178):
        about: -----------------------------------
فردا ، نباید اتفاق بیفتد ...
ما فردا را با انتخاب‌های‌مان می‌سازیم.
        2717 participants, 0 admins, 0 kicked

and in pytg:

{'peer_id': 1002126178, 'id': '$05000000623bbb3b2403f6a04c6bb4e5', 'title': 'کانال الیاس حضرتی', 'participants_count': 2717, 'flags': 65667, 'kicked_count': 0, 'print_name': 'کانال_الیاس_حضرتی', 'admins_count': 0, 'peer_type': 'channel'}

Using pytg

I wish the documentation include some basic examples of how to run pytg. Beside the installation I am not sure if this is to become a module or an active command. Do I kneed o have ./telegram running in a different terminal?

contacts_list does not work

Exception raises when i try to get list of contacts:

sender.contacts_list()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/vonabarak/tgsrv/lib/python3.4/site-packages/pytg-0.4.1rc0-py3.4.egg/pytg/sender.py", line 548, in command_alias
    return self.execute_function(command_name, *args, **kwargs)
  File "/home/vonabarak/tgsrv/lib/python3.4/site-packages/pytg-0.4.1rc0-py3.4.egg/pytg/sender.py", line 275, in execute_function
    return result_parser(message)
  File "/home/vonabarak/tgsrv/lib/python3.4/site-packages/pytg-0.4.1rc0-py3.4.egg/pytg/result_parser.py", line 30, in success_fail
    if json.result == u("SUCCESS"):
AttributeError: 'DictObjectList' object has no attribute 'result'

Probably it should have res.List() instead of res.success_fail in sender.py line 104

Timed Out Error

While I try to use the module in a loop, for example adding bunch of numbers as contact, or removing them or so, I get "timed out" error repeatedly.
The error is below:

Traceback (most recent call last):
File "/usr/local/lib/python3.4/dist-packages/pytg-0.4.1d-py3.4.egg/pytg/sender.py", line 426, in _do_send
answer = self.s.recv(1)
socket.timeout: timed out

Below is an example of how I use the module:

for contact in contact_list:
sender.contact_delete("user#%s" % contact["id"])

error in send message

Hi
I try to use this library but I get this error:

sender.send_msg("some_user", u"nima")
{u'error': u'can not parse arg #1', u'error_code': 38, u'result': u'FAIL'}

I'm using python2.7 and my code is:

tg = Telegram(
telegram="bin/telegram-cli",
pubkey_file="tg-server.pub")
sender = tg.sender

am I missed some thing?

cannot start

A nice package - I want to use ist, but: I have tried both examples
tg.start() gives

tg.start()
Traceback (most recent call last):
File "", line 1, in
File "pytg/init.py", line 30, in start
proc = subprocess.Popen([self._tg, '-k', self._pub], stdin=subprocess.PIPE, stdout=subprocess.PIPE)
File "/usr/local/lib/python2.7/subprocess.py", line 709, in init
errread, errwrite)
File "/usr/local/lib/python2.7/subprocess.py", line 1326, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory

What is wrong?
And - by the way - is there any description how to use this package?

No handlers could be found for logger "pytg.sender"

Trying on the Raspberry pi B and Raspberry pi 2 - No Work :(

nataly@nsa-rp1 ~ $ cat bot.py
from pytg import Telegram
tg = Telegram(
 telegram="/home/nataly/tg/bin/telegram-cli",
 pubkey_file="/home/nataly/tg/server.pub")
receiver = tg.receiver
sender = tg.sender
nataly@nsa-rp1 ~ $ python bot.py
No handlers could be found for logger "pytg.sender"

CPU 100%

When i start pytg my cpu core gets to 100%, is this normal?

Make receiving massages easy.

In Development branch.

Either via

  • Iterator

    for msg in reciever.massages():
        #do shirt
  • Callback

    def foo(msg):
        #do shirt
    
    sender.onmessage(foo)
  • Generators

Adding resolve_username command

It seems that resolve_username command is not in the list of functions in sender.py file altough telegram-cli supports this command. I want to use it for channel_join command because sometimes channel_join doesn't work and need to run resolve_username first.

Starting pytg with nginx

Hi, Im creating web server which sending telegram messages with pytg.
Server hosted on the DigitalOcean hosting.
When a starting server manually (this is flask server) everything works good, but when I start my server with nginx and uwsgi Ive got this error:

open[config_file]: No such file or directory
Traceback (most recent call last):
  File "/opt/rest/app.py", line 34, in <module>
    from resource.Telegram import TelegramAdd
  File "/opt/rest/resource/Telegram.py", line 4, in <module>
    import senders.telegram
  File "/opt/rest/senders/telegram.py", line 11, in <module>
    pubkey_file="/opt/tg/rsa.pub")
  File "build/bdist.linux-x86_64/egg/pytg/__init__.py", line 49, in __init__

So, Im already make sure that way is correct and that www-data have permissions to this file.

Maybe have an idea how I canto fix it? Thankyou in advance!

No pytg module found

Hi
I have installed and compiled the code several times but still cannot import pytg. I get an error that there is no such module.
I am running on a rpi with a virtual environment using Python 2.7.3. I have tg installed and I can send message from the console with the Telegram-cli.

Any suggestions where to look please?

pytg.exceptions.NoResponse

Hi there..

first, i really enjoy and appreciate your work,

i've found some issues like i attached the image below bro

dsc_0164

i don't know whats wrong, my connection seem good..

may be i miss something?

thx

Wait until logged in - Docker

I am trying to dockerize a pytg bot. I encountered this problem:

Sample Code:

tg = Telegram(telegram = TG_CLI, pubkey_file = TG_PUBKEY)
tgSender = tg.sender
try:
    tgSender.send_msg("user#123",'Bot started')
except:
    print('ERROR sending start-msg')

The line tg = Telegram(telegram = TG_CLI, pubkey_file = TG_PUBKEY) will continue after the CLI has started, but before the CLI prompts first time user for phone number, which will result in an error in tgSender.send_msg("user#123",'Bot started') in the following lines.

My question is: how to start the CLI, wait until the user authentication is done, and then proceed to send or receive messages?

can't install

hello

I have an error when execute "make"

here's the output
gcc -g -O2 -I/usr/include/lua5.2 -DHAVE_CONFIG_H -Wall -Wextra -Werror -Wno-deprecated -fno-strict-aliasing -fno-omit-frame-pointer -ggdb -I. -I. -c main.c -o main.o
gcc -g -O2 -I/usr/include/lua5.2 -DHAVE_CONFIG_H -Wall -Wextra -Werror -Wno-deprecated -fno-strict-aliasing -fno-omit-frame-pointer -ggdb -I. -I. -c loop.c -o loop.o
gcc -g -O2 -I/usr/include/lua5.2 -DHAVE_CONFIG_H -Wall -Wextra -Werror -Wno-deprecated -fno-strict-aliasing -fno-omit-frame-pointer -ggdb -I. -I. -c interface.c -o interface.o
interface.c: In function ‘set_interface_callbacks’:
interface.c:1568:3: error: ‘CPPFunction’ is deprecated [-Werror=deprecated-declarations]
rl_attempted_completion_function = (CPPFunction ) complete_text;
^
cc1: all warnings being treated as errors
Makefile:30: recipe for target 'interface.o' failed
make: *
* [interface.o] Error 1

How to save a file which is sent to me?

Hi, Thanks for great API.Can you tell me how can I save a file which is sent to me on my computer using pytg.
I don't know If I should use "load_photo" ? I Couldnt find proper way to use load_photo.
Please advise me.

Thx

bind: Address already in use

try a simple script and the program warns bind: Address already in use on stdout.

from pytg import Telegram
tg = Telegram(telegram="./tg/bin/telegram-cli",
              pubkey_file="./tg/tg-server.pub")

receiver = tg.receiver
sender = tg.sender

sender.send_photo("xxx", "./yyy.jpg")

Does the program correctly close the socket every time when exits?

How to bulk import contacts

I'm trying to add thousands of contacts to my list.
Contacts are saved in a csv formatted file:
Number, First name, Last name
Right now I'm trying to add them one by one in a loop.
Is there any build in feature or can you suggest a better way of doing that?

sender.history() returns only 100 last messages

I want to get maximum number of messages that history command can return, but it only returns 100 last messages. For example this command:

sender.history('$05000000247d0a3cd1ee2ccf1cc3427a', 1000)

pip doesn't seem to pick up the luckydonald-utils dependency

I know i could just install it but i'd expect it to just work™

$ sudo pip install pytg
[sudo] password for dx:
Collecting pytg
  Downloading pytg-0.4.2.tar.gz
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 20, in <module>
      File "/tmp/pip-build-73hkqbzs/pytg/setup.py", line 8, in <module>
        from pytg import VERSION
      File "/tmp/pip-build-73hkqbzs/pytg/pytg/__init__.py", line 9, in <module>
        from luckydonaldUtils.encoding import to_unicode as u
    ImportError: No module named 'luckydonaldUtils'

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-73hkqbzs/pytg
$ pip --version
pip 7.1.2 from /usr/lib/python3.5/site-packages (python 3.5)
$ pip list | grep setuptools
setuptools (18.5)

Exception handler problem in sender

Hi
I found this error after I uploaded a photo with sender.send_photo.

[SUCCESS] dropbox account linked
[INFO] warming up...
[INFO] starting background model...
[UPLOAD] Thursday 15 October 2015 02:01:44PM
[IMAGE] .//b8d38bca-37e1-4e87-a332-58fbfc9a29f9.jpg //*** this is the filename of the image that I upload
No handlers could be found for logger "pytg.sender"
Traceback (most recent call last):
  File "sentry.py", line 159, in <module>
    sender.send_photo("Roaming_Camera", unicode(t.path))
  File "build/bdist.linux-armv7l/egg/pytg/sender.py", line 548, in command_alias
  File "build/bdist.linux-armv7l/egg/pytg/sender.py", line 259, in execute_function
pytg.exceptions.IllegalResponseException: Result parser does not allow exceptions.

Can't make a working bot

I cannot make a simple code to just send a message to someone. Can you provide us with a fully working example that will atleast send and receive one message?

Multiline messages

I needed the ability to send multiline-messages
Since telegram-cli uses "\n" to send the message, I patched it to accept a literal "\n" as a newline instead.
So for a multiline message in python you would write something like this:
"line1\nline2"

diff --git a/queries.c b/queries.c
index ff7ad10..387e7c1 100644
--- a/queries.c
+++ b/queries.c
@@ -910,10 +910,20 @@ void do_send_message (peer_id_t id, const char *msg, int len) {
       return;
     }
   }
+  int newlen = len;
+  char *newmsg = strdup(msg);
+  int i=len-1;
+  for(i=len-1; i>1; --i){
+    if(newmsg[i] == 'n' && newmsg[i-1] == '\\'){
+      newmsg[i-1] = '\n';
+      memmove(newmsg + i, newmsg + i + 1, len -i -1);
+      newlen--;
+    }
+  }
   long long t;
   secure_random (&t, 8);
-  logprintf ("t = %lld, len = %d\n", t, len);
-  bl_do_send_message_text (t, our_id, get_peer_type (id), get_peer_id (id), time (0), len, msg);
+  logprintf ("t = %lld, len = %d\n", t, newlen);
+  bl_do_send_message_text (t, our_id, get_peer_type (id), get_peer_id (id), time (0), newlen, newmsg);
   struct message *M = message_get (t);
   assert (M);
   do_send_msg (M);

How do I install this with pip and run within virtualenv?

well, I activated virtualenv and installed with following commands:

$ git clone https://github.com/efaisal/pytg.git && cd pytg && python setup.py install

but when I run pingbot file, I am getting following error:

(venv)avis-MacBook-Pro:tg avi$ python pytg/pingbot.py
Traceback (most recent call last):
  File "pytg/pingbot.py", line 11, in <module>
    import pytg
  File "/Users/avi/Documents/telegram-bot/tg/pytg/pytg/__init__.py", line 7, in <module>
    from utils import start_pipeline
ImportError: No module named 'utils'

I also tried installing like this, but I am still getting same error:

pip install git+https://github.com/efaisal/pytg.git

New function to create groups

I saw a really necessary-to-solve issue at your patched tg repo this one . It would be great if you can solve it or give me some hint to get over it. thanks

Rich link previews are not working

When sending a link in a message, rich link previews are not working.
Sending a link normally on telegram-cli shows the rich link preview on the receivers client.

Reply not working

The old logic did replies as such:

Old Message IDs

Incoming message

1 [05:29]  luckydonald >>> Test

now we answer that message with id = 1 like this:

[reply=1] msg luckydonald Reply!

The CLI prints

2 [05:29]  luckydonald <<< [reply to ???] Reply!

image

And this is what we get:
image

This already failes.

  • reply to ???
  • replies to something completely different
    • id 1 we got is wrong?

Permanent Message IDs

CLI started with --permanent-msg-ids or --json
image
image

  • not replying to anything?
Reply commands

image
image

  • working

sender.contacts_search() has invalid parser.

Doesn't matter what I put into it, queries that work in telegram-cli don't work at all here.

>>> sender.contacts_search("luckydonald")
DEBUG:pytg.sender:Parsing contacts_search: Argument luckydonald - <user_name> (needed)
DEBUG:pytg.sender:Skipping missing optional parameter #1 [limit] (type NonNegativeNumber) in function contacts_search.
DEBUG:pytg.sender:Sending command > [disable_preview] contact_search 'luckydonald'
<
DEBUG:pytg.sender:Socket Connected.
DEBUG:pytg.sender:All Sent.
Traceback (most recent call last):
  File "/usr/local/lib/python3.4/dist-packages/DictObject/__init__.py", line 435, in __getattr__
    value = dict.__getattribute__(self, n(name))  # Raise exception if not found in original dict's attributes either
AttributeError: 'DictObject' object has no attribute 'result'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/lib/python3.4/dist-packages/DictObject/__init__.py", line 442, in __getattr__
    key_name = self._attribute_to_key_map[n(name)]  # Check if we have this set.
KeyError: 'result'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.4/dist-packages/pytg-0.4.1d-py3.4.egg/pytg/sender.py", line 548, in command_alias
  File "/usr/local/lib/python3.4/dist-packages/pytg-0.4.1d-py3.4.egg/pytg/sender.py", line 275, in execute_function
  File "/usr/local/lib/python3.4/dist-packages/pytg-0.4.1d-py3.4.egg/pytg/result_parser.py", line 30, in success_fail
  File "/usr/local/lib/python3.4/dist-packages/DictObject/__init__.py", line 456, in __getattr__
    raise suppress_context(AttributeError(name))
AttributeError: result

Permission denied in running cli

When i try to run my dumper.py as a periodic task that calls telegram-cli rather than running cli in background manually(test branch is not stable and will crash) , i get open[config_file]: Permission denied error when pytg tries to run cli:

[2016-02-14 19:13:02,692: DEBUG/MainProcess] Task accepted: tasks.run_dumper[fd4bad84-f3d8-4383-b098-3636f62649fe] pid:3788
[2016-02-14 19:13:02,699: INFO/Worker-2] Starting Telegram Executable: "/home/telegramd/tgchannel/tg/bin/telegram-cli -R -W -P 4458 -k /home/telegramd/tgchannel/tg/server.pub --json"
[2016-02-14 19:13:02,703: DEBUG/Worker-2] Parsing raw: Argument help - <command> (needed)
[2016-02-14 19:13:02,704: DEBUG/Worker-2] Sending command > [disable_preview]  help
<
open[config_file]: Permission denied
[2016-02-14 19:13:02,709: INFO/Worker-2] CLI did not responde.
[2016-02-14 19:13:03,710: DEBUG/Worker-2] Parsing raw: Argument help - <command> (needed)
[2016-02-14 19:13:03,711: DEBUG/Worker-2] Sending command > [disable_preview]  help
<
[2016-02-14 19:13:03,711: INFO/Worker-2] CLI did not responde.
[2016-02-14 19:13:04,716: ERROR/MainProcess] Task tasks.run_dumper[fd4bad84-f3d8-4383-b098-3636f62649fe] raised unexpected: AssertionError('CLI Process died.',)
Traceback (most recent call last):
  File "/usr/local/lib/python3.4/site-packages/celery/app/trace.py", line 240, in trace_task
    R = retval = fun(*args, **kwargs)
  File "/usr/local/lib/python3.4/site-packages/celery/app/trace.py", line 438, in __protected_call__
    return self.run(*args, **kwargs)
  File "/home/telegramd/telegram_dumper/tasks.py", line 13, in run_dumper
    main()
  File "/home/telegramd/telegram_dumper/dumper.py", line 170, in main
    pubkey_file="/home/telegramd/tgchannel/tg/server.pub")
  File "/usr/local/lib/python3.4/site-packages/pytg-0.4.5-py3.4.egg/pytg/__init__.py", line 50, in __init__
AssertionError: CLI Process died.

P.S: i'm running pytg as daemon in supervisord.

Huge Update, Version 0.4.1

Good news:
Pytg is up to date!
I took maintainance of this Project and merged my fork pytg2 into this.
There is a How to Update section in the readme.
If there are any questions left uncovered, ask away.
Thanks!

coroutine decorator is missing call to @wraps

Thanks for this really useful lib! Here is my little contribution:

coroutine() decorator at utils.py module is missing wraps decorator. Reference here.

Proposed fix (using python 2.7):

from functools import wraps


def coroutine(func):
    """
    Skips to the first yield when the generator is created.
    Used as decorator, @coroutine
    :param func: function (generator) with yield.
    :return: generator
    """

    @wraps(func)  # <== Added @wraps here
    def start(*args, **kwargs):
        try:
            cr = func(*args, **kwargs)
            try:
                next(cr)
            except NameError:  # not defined, python 2
                cr.next()
            return cr
        except StopIteration:
            return
        except KeyboardInterrupt:
            raise StopIteration

    return start

IllegalResponseException instead of NoResponse

Your basic code with my code

from pytg.utils import coroutine
from pytg.sender import Sender
from pytg.receiver import Receiver
receiver = Receiver(host="localhost", port=4458)
sender = Sender(host="localhost", port=4458)


@coroutine # from pytg.utils import coroutine
def main_loop():
    while not QUIT:
        msg = (yield) # it waits until it got a message, stored now in msg.
        print("Message: ", msg.text)
        # do more stuff here!

sender.send_msg("Patrick", "Hallo")

receiver.start()
receiver.message(main_loop())

The Error's

Result parser does not allow exceptions, but we got one:
Traceback (most recent call last):
  File "/usr/local/lib/python3.2/dist-packages/pytg-0.4.1d-py3.2.egg/pytg/sender.py", line 426, in _do_send
    answer = self.s.recv(1)
socket.timeout: timed out

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/lib/python3.2/dist-packages/pytg-0.4.1d-py3.2.egg/pytg/sender.py", line 250, in execute_function
    result = self._do_command(command_name, new_args, answer_timeout=result_timeout, retry_connect=retry_connect, enable_preview=enable_preview, reply_id=reply_id)
  File "/usr/local/lib/python3.2/dist-packages/pytg-0.4.1d-py3.2.egg/pytg/sender.py", line 359, in _do_command
    result = self._do_send(request, answer_timeout=answer_timeout, retry_connect=retry_connect)
  File "/usr/local/lib/python3.2/dist-packages/pytg-0.4.1d-py3.2.egg/pytg/sender.py", line 449, in _do_send
    raise NoResponse(command)
pytg.exceptions.NoResponse:  [disable_preview] msg Patrick 'Hallo'

Traceback (most recent call last):
  File "/usr/local/lib/python3.2/dist-packages/pytg-0.4.1d-py3.2.egg/pytg/sender.py", line 426, in _do_send
    answer = self.s.recv(1)
socket.timeout: timed out

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/usr/local/lib/python3.2/dist-packages/pytg-0.4.1d-py3.2.egg/pytg/sender.py", line 250, in execute_function
    result = self._do_command(command_name, new_args, answer_timeout=result_timeout, retry_connect=retry_connect, enable_preview=enable_preview, reply_id=reply_id)
  File "/usr/local/lib/python3.2/dist-packages/pytg-0.4.1d-py3.2.egg/pytg/sender.py", line 359, in _do_command
    result = self._do_send(request, answer_timeout=answer_timeout, retry_connect=retry_connect)
  File "/usr/local/lib/python3.2/dist-packages/pytg-0.4.1d-py3.2.egg/pytg/sender.py", line 449, in _do_send
    raise NoResponse(command)
pytg.exceptions.NoResponse:  [disable_preview] msg Patrick 'Hallo'


During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "a.py", line 15, in <module>
    sender.send_msg("Patrick", "Hallo")
  File "/usr/local/lib/python3.2/dist-packages/pytg-0.4.1d-py3.2.egg/pytg/sender.py", line 548, in command_alias
    return self.execute_function(command_name, *args, **kwargs)
  File "/usr/local/lib/python3.2/dist-packages/pytg-0.4.1d-py3.2.egg/pytg/sender.py", line 259, in execute_function
    raise IllegalResponseException("Result parser does not allow exceptions.")
pytg.exceptions.IllegalResponseException: Result parser does not allow exceptions.
Terminating currently sending request.

I Started the Client and he dosent give me a error. I will try to find the Error by the client.. Mybe you know what I am doing wrong ... (Using Python3.2)

'DictObject' object has no attribute 'text'

Crush becouse of image recieved.
Python3.
Traceback (most recent call last):
File "/home/administrator/tgbot/tgbotenv/lib/python3.4/site-packages/DictObject-0.1.1-py3.4.egg/DictObject/init.py", line 434, in getattr
AttributeError: 'DictObject' object has no attribute 'text'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/home/administrator/tgbot/tgbotenv/lib/python3.4/site-packages/DictObject-0.1.1-py3.4.egg/DictObject/init.py", line 441, in getattr
KeyError: 'text'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "tgbotmain.py", line 54, in
main() # executing main function # Last command of file (so everything needed is already loaded above)
File "tgbotmain.py", line 16, in main
receiver.message(example_function(sender)) # now it will call the example_function and yield the new messages.
File "/home/administrator/tgbot/tgbotenv/lib/python3.4/site-packages/pytg-0.4.1b0-py3.4.egg/pytg/utils.py", line 29, in start
File "/home/administrator/tgbot/tgbotenv/lib/python3.4/site-packages/pytg-0.4.1b0-py3.4.egg/pytg/receiver.py", line 217, in message
File "tgbotmain.py", line 36, in example_function
if msg.text is not str: # we have media instead.
File "/home/administrator/tgbot/tgbotenv/lib/python3.4/site-packages/DictObject-0.1.1-py3.4.egg/DictObject/init.py", line 455, in getattr
AttributeError: text
Terminating currently sending request.

changes in last version of Telegram Cli

last version of Telegram Cli rename settings path, that must be fixed in pytg
in init.py , line 120

#was 
authfile = os.path.join(os.environ['HOME'], '.telegram', 'auth')
#now:
authfile = os.path.join(os.environ['HOME'], '.telegram-cli', 'auth')

Unable to get a specific number of messages from history

Hi,
I am trying to save the chat history into a file. However, when I use the execute_function function, I always get 40 results (the default number)

n_messages = 0
for message in sender.execute_function('history', 'my_contact', '10'):
    n_messages += 1
# It is always 40
print(n_messages)

What is the way for specify the size of the history?

Thanks!

Implement contact_search

Send messages to people by there usernames

I want to send messages to users by their usernames (without knowing their phone number). In the CLI i can do "contact_search @username" and the output contains the the real name which I can use to message the person directly.

I can't find out how this can be implemented with this wrapper. How can I archived that?

Cannot use sender

When sender is imported i crash with the error

File "build/bdist.macosx-10.6-intel/egg/pytg/__init__.py", line 22, in __init__
  File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pytg-0.4.1-py2.7.egg/pytg/sender.py", line 204
    def execute_function(self, function_name, *arguments, reply_id=None, enable_preview=None, **kwargs):
                                                                 ^
SyntaxError: invalid syntax

I didnot receive message

I installed and sent message successfully, but i cannot create a program for receiving messsage from other user . i did as same file https://github.com/luckydonald/pytg/blob/master/examples/dump.py but nothing happend

This is my code

from pytg.utils import coroutine
@coroutine # from pytg.utils import coroutine
def main_loop():
    while True:
        msg = (yield) # it waits until it got a message, stored now in msg.
        print("Message: ", msg.text)

from pytg import Telegram
tg = Telegram(
        telegram="/home/vagrant/telegram/tg/bin/telegram-cli",
        pubkey_file="/home/vagrant/telegram/tg/tg-server.pub")

receiver = tg.receiver
receiver.start()
receiver.message(main_loop())

And i used other accout to send to this account. but the message did display on console.
Thanks

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.