How to create a telegram investment bot
How to create a Telegram BOT step by step typing no code | by Antonio Mignano
Simple autoresponder to entertain your friends
Photo by Christian Wiediger on UnsplashTelegram is one of the most used program for instant messaging and it is known for the possibility to have bots that interact with user privately or within groups.
Some of these bots are very useful and some of them are just meant to be fun.
In this tutorial we are going to create our own bot without worring about any code.
We will need this in order to run the bot on our computer (or for the ones a little bit nerdier on a Raspberry).
So, let’s download it from here: https://nodejs.org/en/download/
This is the link from GitHub where to download all the material needed to configure and run the bot: Download
The whole project (let me call it this way, I don’t want to use the word “code” to not scare anyone) is on GitHub:
Xfox1/telegrambotautoresponder
A simple little framework to create an autoresponder bot for telegram.
- Xfox1/telegrambotautorespondergithub.com
In order to create a bot we need to obtain an official code from Telegram (called API token), and for that we have to contact BotFather: https://t.me/botfather
BotFather is the one bot to rule them all. Use it to create new bot accounts and manage your existing bots.
Just type the command /newbot and follow the istructions given by BotFather:
Another important step we better do now is to disable the privacy of the bot to allow it inside group chats.
Simply send the command /setprivacy to Botfather, select your bot and click/tap on disable.
If you haven’t done it yet unzip the project inside a folder then rename .envExample to .env (see later if you’re on Windows) and edit the following line, inserting your API token given by BotFather:
TELEGRAM_TOKEN=”<YOUR_TOKEN_HERE>”
If you are on Windows:
You may have trouble renaming the file, simply open the start menu and type “cmd” then open the “Command Prompt” and do as this image:
Now it’s time to be creative.
Open the file answers.json and let’s give a look at it.
Here’s where all the answers are stored, it’s easy to see the structure, a concatenation of these “objects” that contain the triggers and the replies to each of those triggers.
Of course this is just an example with 3 answers, you can have a lot more.
Let’s analyze how it is composed:
- triggers: concatenation of strings that trigger that answer
- replies: concatenation of a “sub-ojects”
Each one of the replies has
- reply: which is what is meant to be sent as message
- type: it specify the type of the reply, can be “text”, “audio” , “image” or “response”
Depending on the type, the reply should have a meaningful value: in case the type is equal to audio or image the value of reply must be a valid path to a file on your computer even if it is highly suggested to put these kind of media inside the folder “media”.
As for now the extentions tested for media are “.jpg”, “.gif” and “.mp3”.
Edit October 2021: introduced type “response”, in which the bot will quote the message it is answering to. It is also possible to inser hyperlinks in HTML format.
On a Command Prompt type the following command (inside the folder of the project) in order to download all the dependecies needed by the bot:
npm install
We are almost done, now that everything is set up with can finally start our bot. In the same console we used to install all the dependencies we have to run:
npm start
And this is the result
You may notice that in the console there are some [INFO] messages, those help you keep track of who is using your bot, the same information are stored inside a file you’ll find in the project folder called debug.log.
The bot can be stopped and rerun without any problem
In case you want to run it on a headless machine, like a Raspberry, you may want to find a way to have it not interfering with other application, read my other article about Unix Screen:
Unix Screen, the very few commands you should know
And how to autorun different screen on startup
medium. comW
How to Create a Telegram Bot
Chatbots are often touted as a revolution in the way users interact with technology and businesses. They have a fairly simple interface compared with traditional apps, as they only require users to chat, and the chatbots are supposed to understand and do whatever the user demands from them, at least in theory.
Many industries are shifting their customer service to chatbot systems. That’s because of the huge drop in the cost compared to actual humans, and also because of the robustness and constant availability. Chatbots deliver a degree of user support without substantial additional cost.
Today, chatbots are used in many scenarios, ranging from menial tasks such as displaying time and weather data to more complex operations such as rudimentary medical diagnosis and customer communication/support. You can devise a chatbot that will help your customers when they ask certain questions about your product, or you can make a personal assistant chatbot that can handle basic tasks and remind you when it’s time to head to a meeting or the gym.
There are a lot of options when it comes to where you can deploy your chatbot, and one of the most common uses are social media platforms, as most people use them on a regular basis. The same can be said of instant messaging apps, though with some caveats.
Telegram is one of the more popular IM platforms today, as it allows you to store messages on the cloud instead of just your device and it boasts good multi-platform support, as you can have Telegram on Android, iOS, Windows, and just about any other platform that can support the web version. Building a chatbot on Telegram is fairly simple and requires few steps that take very little time to complete. The chatbot can be integrated in Telegram groups and channels, and it also works on its own.
In this tutorial, we will be creating a Telegram bot that gives you an avatar image from Adorable Avatars. Our example will involve building a bot using Flask and deploying it on a free Heroku server.
To complete this tutorial, you will need Python 3 installed on your system as well as Python coding skills. Also, a good understanding of how apps work would be a good addition, but not a must, as we will be going through most of the stuff we present in detail. You also need Git installed on your system.
Of course, the tutorial also requires a Telegram account, which is free. You can sign up here. A Heroku account is required, too, and you can get it for free here.
Bringing Your Telegram Bot to Life
To create a chatbot on Telegram, you need to contact the BotFather, which is essentially a bot used to create other bots.
The command you need is /newbot
which leads to the following steps to create your bot:
Your bot should have two attributes: a name and a username. The name will show up for your bot, while the username will be used for mentions and sharing.
After choosing your bot name and username—which must end with “bot”—you will get a message containing your access token, and you’ll obviously need to save your access token and username for later, as you will be needing them.
Code the Chatbot Logic
We will be using Ubuntu in this tutorial. For Windows users, most of the commands here will work without any problems, but should you face any issues with the virtual environment setup, please consult this link. As for Mac users, this tutorial should work just fine.
First, let’s create a virtual environment. It helps isolate your project’s requirements from your global Python environment.
$ python -m venv botenv/
Now we will have a botenv/
directory which will contain all the Python libraries we will be using. Go ahead and activate virtualenv
using the following command:
$ source botenv/bin/activate
The libraries we need for our bot are:
- Flask: A micro web framework built in Python.
- Python-telegram-bot: A Telegram wrapper in Python.
- Requests: A popular Python http library.
You can install them in the virtual environment using pip command as follows:
(telebot) $ pip install flask (telebot) $ pip install python-telegram-bot (telebot) $ pip install requests
Now let’s browse our project directory.
. ├── app.py ├── telebot │ ├── credentials.py │ | . │ | you can build your engine here │ | . │ └── __init__.py └── botenv
In the credentials.py
file we will need three variables:
bot_token = "here goes your access token from BotFather" bot_user_name = "the username you entered" URL = "the heroku app link that we will create later"
Now let’s go back to our app.py and go through the code step by step:
# import everything from flask import Flask, request import telegram from telebot.credentials import bot_token, bot_user_name,URL
global bot global TOKEN TOKEN = bot_token bot = telegram.Bot(token=TOKEN)
Now we have the bot object which will be used for any action we require the bot to perform.
# start the flask app app = Flask(__name__)
We also need to bind functions to specific routes. In other words, we need to tell Flask what to do when a specific address is called. More detailed info about Flask and routes can be found here.
In our example, the route function responds to a URL which is basically /{token}
, and this is the URL Telegram will call to get responses for messages sent to the bot.
@app.route('/{}'.format(TOKEN), methods=['POST']) def respond(): # retrieve the message in JSON and then transform it to Telegram object update = telegram.Update.de_json(request.get_json(force=True), bot) chat_id = update.message.chat.id msg_id = update.message.message_id # Telegram understands UTF-8, so encode text for unicode compatibility text = update.message.text.encode('utf-8').decode() # for debugging purposes only print("got text message :", text) # the first time you chat with the bot AKA the welcoming message if text == "/start": # print the welcoming message bot_welcome = """ Welcome to coolAvatar bot, the bot is using the service from http://avatars.adorable.io/ to generate cool looking avatars based on the name you enter so please enter a name and the bot will reply with an avatar for your name. """ # send the welcoming message bot.sendMessage(chat_id=chat_id, text=bot_welcome, reply_to_message_id=msg_id) else: try: # clear the message we got from any non alphabets text = re.sub(r"\W", "_", text) # create the api link for the avatar based on http://avatars.adorable.io/ url = "https://api.adorable.io/avatars/285/{}.png".format(text.strip()) # reply with a photo to the name the user sent, # note that you can send photos by url and telegram will fetch it for you bot.sendPhoto(chat_id=chat_id, photo=url, reply_to_message_id=msg_id) except Exception: # if things went wrong bot.sendMessage(chat_id=chat_id, text="There was a problem in the name you used, please enter different name", reply_to_message_id=msg_id) return 'ok'
The intuitive way to make this function to work is that we will call it every second, so that it checks whether a new message has arrived, but we won’t be doing that. Instead, we will be using Webhook which provides us a way of letting the bot call our server whenever a message is called, so that we don’t need to make our server suffer in a while loop waiting for a message to come.
So, we will make a function that we ourself need to call to activate the Webhook of Telegram, basically telling Telegram to call a specific link when a new message arrives. We will call this function one time only, when we first create the bot. If you change the app link, then you will need to run this function again with the new link you have.
The route here can be anything; you’re the one who will call it:
@app.route('/setwebhook', methods=['GET', 'POST']) def set_webhook(): # we use the bot object to link the bot to our app which live # in the link provided by URL s = bot.setWebhook('{URL}{HOOK}'.format(URL=URL, HOOK=TOKEN)) # something to let us know things work if s: return "webhook setup ok" else: return "webhook setup failed"
Now that everything is set, let’s just make a fancy homepage so that we know the engine is up.
@app.route('/') def index(): return '.' if __name__ == '__main__': # note the threaded arg which allow # your app to have more than one thread app.run(threaded=True)
Let’s take a look at the full version of app.py:
import re from flask import Flask, request import telegram from telebot.credentials import bot_token, bot_user_name,URL global bot global TOKEN TOKEN = bot_token bot = telegram.Bot(token=TOKEN) app = Flask(__name__) @app.route('/{}'.format(TOKEN), methods=['POST']) def respond(): # retrieve the message in JSON and then transform it to Telegram object update = telegram.Update.de_json(request.get_json(force=True), bot) chat_id = update.message.chat.id msg_id = update.message.message_id # Telegram understands UTF-8, so encode text for unicode compatibility text = update.message.text.encode('utf-8').decode() # for debugging purposes only print("got text message :", text) # the first time you chat with the bot AKA the welcoming message if text == "/start": # print the welcoming message bot_welcome = """ Welcome to coolAvatar bot, the bot is using the service from http://avatars. adorable.io/ to generate cool looking avatars based on the name you enter so please enter a name and the bot will reply with an avatar for your name. """ # send the welcoming message bot.sendMessage(chat_id=chat_id, text=bot_welcome, reply_to_message_id=msg_id) else: try: # clear the message we got from any non alphabets text = re.sub(r"\W", "_", text) # create the api link for the avatar based on http://avatars.adorable.io/ url = "https://api.adorable.io/avatars/285/{}.png".format(text.strip()) # reply with a photo to the name the user sent, # note that you can send photos by url and telegram will fetch it for you bot.sendPhoto(chat_id=chat_id, photo=url, reply_to_message_id=msg_id) except Exception: # if things went wrong bot.sendMessage(chat_id=chat_id, text="There was a problem in the name you used, please enter different name", reply_to_message_id=msg_id) return 'ok' @app. route('/set_webhook', methods=['GET', 'POST']) def set_webhook(): s = bot.setWebhook('{URL}{HOOK}'.format(URL=URL, HOOK=TOKEN)) if s: return "webhook setup ok" else: return "webhook setup failed" @app.route('/') def index(): return '.' if __name__ == '__main__': app.run(threaded=True)
That’s the last bit of code you will write in our tutorial. Now we can progress to the last step, launching our app on Heroku.
Launch Our App on Heroku
We need a couple of things before we make our app.
Heroku can’t know what libraries your project uses, so we have to tell it using the requirements.txt
file—a common problem is that you misspell requirements, so be careful—to generate the requirements file using pip:
pip freeze > requirements.txt
Now you have your requirements file ready to go.
Now you need the Procfile
which tells Heroku where our app starts, so create a Procfile
file and add the following:
web: gunicorn app:app
A bounce step: You can add a . gitignore
file to your project so that no-use files don’t get uploaded to the repository.
From your Heroku dashboard, create a new app. Once you do, it will direct you to the Deploy page. Then, open the Settings tab in a new window and copy the domain of the app which will be something like https://appname.herokuapp.com/
and paste it in the URL variable inside credentials.py
.
Now, go back to the Deploy tab and proceed with the steps:
Note: Windows and macOS users can follow the steps described here.
Log in to Heroku:
$ heroku login
Please note that this method sometimes gets stuck in waiting for login
, if this happens to you, try to log in using:
$ heroku login -i
Initialize a Git repository in our directory:
$ git init $ heroku git:remote -a {heroku-project-name}
Deploy the app:
$ git add . $ git commit -m "first commit" $ git push heroku master
At this point, you will see the building progress in your terminal. If everything went okay, you will see something like this:
remote: -----> Launching... remote: Released v6 remote: https://project-name.herokuapp.com/ deployed to Heroku remote: remote: Verifying deploy... done.
Now go to the app page (the link of the domain you copied before) and add to the end of the link /setwebhook
so that the address will be something like https://appname.herokuapp.com/setwebhook
. If you see webhook setup ok
, that means you are ready to go!
Now Go Talk to Your Bot
A live version of the bot
Finishing Touches, Tips, and Tricks
Now you have your Telegram bot up and running, 24/7, without any need for your intervention. You can add whatever logic you want to the bot, so, for example, you can make your bot more realistic by adding a “typing” status and sending a photo status as follows:
The next code snippet from the respond()
function:
if text == "/start": # print the welcoming message bot_welcome = """ Welcome to coolAvatar bot, the bot is using the service from http://avatars. adorable.io/ to generate cool looking avatars based on the name you enter so please enter a name and the bot will reply with an avatar for your name. """ # send the welcoming message bot.sendChatAction(chat_id=chat_id, action="typing") sleep(1.5) bot.sendMessage(chat_id=chat_id, text=bot_welcome, reply_to_message_id=msg_id) else: try: # clear the message we got from any non alphabets text = re.sub(r"\W", "_", text) # create the api link for the avatar based on http://avatars.adorable.io/ url = "https://api.adorable.io/avatars/285/{}.png".format(text.strip()) # reply with a photo to the name the user sent, # note that you can send photos by url and telegram will fetch it for you bot.sendChatAction(chat_id=chat_id, action="upload_photo") sleep(2) bot.sendPhoto(chat_id=chat_id, photo=url, reply_to_message_id=msg_id) except Exception: # if things went wrong bot. sendMessage(chat_id=chat_id, text="There was a problem in the name you used, please enter different name", reply_to_message_id=msg_id)
As you can see in the snippet, we added a typing action when we are about to send the information about the bot which is in text format, and added an upload photo action when we are about to send a photo to make the bot more realistic. More actions can be found here.
You can also change the bot image and description from the BotFather channel to make it more friendly.
Many more simple examples of telegram bots can be found on the python-telegram-bot page on GitHub.
You can build upon our bot and make it the next super AI bot—all you need to do is to integrate your logic in the respond()
function. For example, your logic can be in a separate module and can be called inside of the respond()
function like so:
. ├── app.py ├── telebot │ ├── credentials.py │ ├──ai.py │ | . │ | you can build your engine here │ | . │ └── __init__.py └── botenv
And inside of ai.py :
def generate_smart_reply(text): # here we can do all our work return "this is a smart reply from the ai!"
Import it now in the app.py :
import re from time import sleep from flask import Flask, request import telegram From telebot.ai import generate_smart_reply from telebot.credentials import bot_token, bot_user_name,URL
Then just call it inside of the respond()
code.
def respond(): # retrieve the message in JSON and then transform it to Telegram object update = telegram.Update.de_json(request.get_json(force=True), bot) chat_id = update.message.chat.id msg_id = update.message.message_id # Telegram understands UTF-8, so encode text for unicode compatibility text = update.message.text.encode('utf-8').decode() # for debugging purposes only print("got text message :", text) # here call your smart reply message reply = generate_smart_reply(text) bot. sendMessage(chat_id=chat_id, text=reply, reply_to_message_id=msg_id)
Now you can have your bot work the way you want—go ahead and create the next big thing!
I hope you had fun building your first Telegram bot.
Additional Resources
- Building a Chatbot using Telegram and Python
- Setting your Telegram Bot WebHook the easy way
- Python-telegram-bot Repository
- Deploying with Git on Heroku
- Python Telegram Bot documentation
Related: Create a WhatsApp Chatbot, Not an App
How telegram bots help an investor. Overview of useful and free bots - Finance on vc.ru
Somehow unnoticed, Telegram has become one of the main sources of information for investors, at least in the CIS.
10,090 views
But not only telegram channels are strong this messenger. One of the key features of Telegram has always been bots, of which there are a great many. But what is strange, for investors, I managed to find just a few useful ones. I would be glad if in the comments you provide links to the bots that you use yourself. nine0003
Below is my top free and useful telegram bots.
For lovers of dividends
I myself love the dividend investment strategy. One of my portfolios is fully focused on receiving and reinvesting dividends. The bot https://t.me/DividendsBroBot is very convenient for tracking dividend stories. The bot has a lot of settings, which allows you to configure it as flexibly as possible. A convenient feature is notification of dividend cut-offs in the current month. The bot supports both foreign stocks and Russian issuers. In general, a must have thing! nine0003
For those who want to quickly find out analysts' forecasts
When there are several ideas in your head, but there is not much money to buy, it is useful to look at analysts' forecasts and come to a final decision based on them. As they say, one head is good, but 30 is better :)
For quick information on analysts' forecasts, I use the bot https://t. me/MyWallStreetBot. The bot uses the sites nasdaq.com, marketbeat.com, tipranks.com. Enter the desired ticker and get a price forecast and recommendations to buy, sell or hold. For example, for Microsoft:
The downside is that the bot is focused only on foreign stocks. However, for me personally, this is not a minus, I still don’t invest in Russian ones :)
For those who like to spy on Catherine Wood
The next bot is designed to receive operational information about what Ark Invest funds buy and sell. The bot is available at https://t.me/ARKlyBot. Data on all transactions of the fund is on their website and is not some kind of classified information. Just through the bot you can get information faster and in a convenient way. nine0003
Here, for example, is the report from the bot for Friday September 9th:
It clearly shows which shares were bought and which were sold by Ark Invest funds.
For convenient portfolio management
Another cool free bot is https://t. me/PocketStockBot. In this bot, you can keep a record of purchased shares. There is a handy log that stores all transactions. The mode of displaying the entire portfolio with the dynamics of its changes. It is possible to quickly find out the stock quote in rubles and dollars. nine0003
For me, the minus is that the bot works with reference to the Moscow Exchange, which means that all calculations are made in rubles. But for many, I think this is not a problem.
You will find even more useful materials about investing in my Telegram channel "Investing Step by Step".
Successful investment!
Mirocana — system and Telegram bot for automatic investments — Tribuna on vc.ru
The system evaluates stocks and currencies using artificial intelligence algorithms. nine0003
14 625 views
Hello. My name is George, I'm 20 years old, I live in St. Petersburg, I work as a back-end developer in a company that makes mobile games. In addition, I am engaged in data analysis, developing Mirocana. com for the last year and a half. It is a forecasting system that looks for investment opportunities by determining which stocks and currencies are undervalued and which are overvalued.
For high-quality forecasting, a large amount of data is analyzed in real time: quotes, news, financial releases, activity of other funds, fundamental statistics on companies and other data. In addition, the bot manages virtual funds. You can read more about the analysis process at the link, you can also try to build your own small neural network and train it to solve simple problems. nine0003
I have developed the MirocanaBot Telegram bot, which makes investing simple and interesting using forecasts.
So far only in English, translations into other languages are under development. You can participate in this: if you write the "/translate" command, the bot will offer to add your own translations or evaluate the quality of those that already exist.
In the beginning, he will open a virtual account for you for $10,000, which he will begin to manage. It will periodically open and close positions based on forecasts, notifying you of this. You can always review open positions and close those you are not sure about. nine0003
You can also share your investment results and view financial data and news on any public company via inline mode or by writing a question. All financial indicators that the bot displays are constantly updated with a slight delay.
New positions are opened only in accordance with the forecasts generated by Mirocana - the user cannot open a new trade on his own. This is done in order to prevent possible consequences and negative experiences from a bad investment. nine0003
Potential
-
The chat format is perfect for such a service. In this way, a high level of personalization, engagement and user trust can be achieved using personal appeals, calls for replicas from the past (bot memory illusion) and replicas on abstract topics that evoke emotions, which is not available to a dry web interface.
- I started developing this project in order to invest my funds wisely. While testing the bot among my friends, I noticed that the topic of investing their savings is of interest to a large circle of people, even those who do not have savings. Due to the lack of knowledge of how to take the first step, the fear of losing or being deceived, and the lack of free time, they prefer to keep their savings in cash or on a bank deposit. The latest BlackRock study confirms that the situation is similar in the US. nine0076
Development plans
-
The most important thing in this project is forecasting accuracy. I will gradually increase the set of tools - now limited by free time and servers. I will also hold a forecasting tournament among data scientists, which will increase the accuracy of the models.
-
Before developing further, you need to make sure that the bot closes most of the user's popular questions and replies (I periodically review unrecognized replies and add answers for them), and also need to professionally translate it into popular languages.