Running Python Code in Telegram Messages

TGPy runs Python code you send in your Telegram chats. It feels like magic: the output appears just below the code.

Now you can quickly calculate something while chatting with friends or coworkers — or check out Python libraries when talking about code. If you are ready to go advanced, you can even use Telegram features to automate sending messages or collect statistics across your chats.

For more use cases, visit TGPy Recipes or our Russian-speaking Telegram chat.

How it works

Let’s dive into some technical details.

TGPy is a Telegram client app. You start TGPy on your local machine or a server, and it starts listening to the messages you send.

For each message, TGPy checks if it is a valid Python code (by parsing AST and comparing if the words in the text are known functions and variables.) If this is indeed code, TGPy runs the code and edits it to write the returned value.

There are also various hacks implemented so that it’s easier to type tiny code snippets: the variables are saved across messages, await keyword can be used top-level (and even as method), and so on.

TGPy is written with Telethon library and provides you with handy ways to use Telethon functions and objects — so your code can easily reply to messages, pin them, etc.

Project status

I designed and coded initial version of TGPy; now, Vanutp maintains the project.

I also spent a lot of time setting up and writing the documentation. I believe it turned out somewhat helpful and extensive!

You can check the docs out.