├── Procfile ├── requirements.txt ├── LICENSE ├── bot.py └── README.md /Procfile: -------------------------------------------------------------------------------- 1 | web: python3 bot.py -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | python-telegram-bot==12.7 2 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Liu Haohui 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /bot.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from telegram.ext import Updater, CommandHandler, MessageHandler, Filters 3 | import os 4 | PORT = int(os.environ.get('PORT', '8443')) 5 | 6 | # Enable logging 7 | logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', 8 | level=logging.INFO) 9 | 10 | logger = logging.getLogger(__name__) 11 | TOKEN = 'YOURTELEGRAMBOTTOKEN' 12 | 13 | # Define a few command handlers. These usually take the two arguments update and 14 | # context. Error handlers also receive the raised TelegramError object in error. 15 | def start(update, context): 16 | """Send a message when the command /start is issued.""" 17 | update.message.reply_text('Hi!') 18 | 19 | def help(update, context): 20 | """Send a message when the command /help is issued.""" 21 | update.message.reply_text('Help!') 22 | 23 | def echo(update, context): 24 | """Echo the user message.""" 25 | update.message.reply_text(update.message.text) 26 | 27 | def error(update, context): 28 | """Log Errors caused by Updates.""" 29 | logger.warning('Update "%s" caused error "%s"', update, context.error) 30 | 31 | def main(): 32 | """Start the bot.""" 33 | # Create the Updater and pass it your bot's token. 34 | # Make sure to set use_context=True to use the new context based callbacks 35 | # Post version 12 this will no longer be necessary 36 | updater = Updater(TOKEN, use_context=True) 37 | 38 | # Get the dispatcher to register handlers 39 | dp = updater.dispatcher 40 | 41 | # on different commands - answer in Telegram 42 | dp.add_handler(CommandHandler("start", start)) 43 | dp.add_handler(CommandHandler("help", help)) 44 | 45 | # on noncommand i.e message - echo the message on Telegram 46 | dp.add_handler(MessageHandler(Filters.text, echo)) 47 | 48 | # log all errors 49 | dp.add_error_handler(error) 50 | 51 | # Start the Bot 52 | updater.start_webhook( 53 | listen="0.0.0.0", 54 | port=int(PORT), 55 | url_path=TOKEN, 56 | webhook_url='https://yourherokuappname.herokuapp.com/' + TOKEN 57 | ) 58 | 59 | # Run the bot until you press Ctrl-C or the process receives SIGINT, 60 | # SIGTERM or SIGABRT. This should be used most of the time, since 61 | # start_polling() is non-blocking and will stop the bot gracefully. 62 | updater.idle() 63 | 64 | if __name__ == '__main__': 65 | main() -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # python-telegram-bot-heroku 4 | A guide to hosting a telegram bot created using the python-telegram-bot library with heroku. 5 | ![Deploy your Ember project to Heroku from Github - Philip Mutua ...](https://miro.medium.com/max/3600/1*fIjRtO5P8zc3pjs0E5hYkw.png) 6 | See the full article explaining the steps [here](https://towardsdatascience.com/how-to-deploy-a-telegram-bot-using-heroku-for-free-9436f89575d2). 7 | 8 | ## Getting Started 9 | Before you begin, you will need a Telegram bot API token from [BotFather](https://t.me/botfather). 10 | 11 | 1. Download the three files in this repo: bot.py (containing your python code for the Telegram bot), requirements.txt (containing the python libraries to be installed), and Procfile (containing the command to execute the python file). 12 | 2. Login / [create](https://signup.heroku.com/dc) a Heroku account. 13 | 3. Install [Git](https://git-scm.com/book/en/v2/Getting-Started-Installing-Git). 14 | 4. Install the [Heroku CLI](https://devcenter.heroku.com/articles/getting-started-with-python#set-up). 15 | 5. Once installed, you can use the _heroku_ command in your terminal / command prompt. Go to the same directory as the files in this repository, and type: 16 | 17 | > heroku login 18 | 19 | A new window will be opened in your browser prompting you to login, so just click on the button. 20 | 21 | 6. Once you are logged in, go back to the command line. Type in 22 | > heroku create 23 | 24 | to create your new webapp. Heroku will assign your webapp a name as well as the link to your webapp, which should be of the format [https://{yourherokuappname}.herokuapp.com/.](https://yourherokuappname.herokuapp.com/.) 25 | 26 | 7. To the bot.py file, change the TOKEN variable to the API token of your telegram bot, and change the yourherokuappname to the name of your heroku app in the line 27 | 28 | > updater.bot.setWebhook('https://yourherokuappname.herokuapp.com/' + TOKEN) 29 | 30 | 8. Next, in your command line, type the following commands in the following order: 31 | 32 | > git init 33 | > git add . 34 | > git commit -m "first commit" 35 | 36 | > heroku git:remote -a YourAppName 37 | 38 | > git push heroku master 39 | 40 | (Make sure to replace YourAppName with the name of your Heroku webapp) 41 | 42 | You should then see the following messages: 43 | 44 | ![](https://cdn-images-1.medium.com/max/1000/1*y3JH7a7mY4oYFaAjDCA1Ow.png) 45 | 46 | In particular, it will say that a Python app is detected and it will install the required libraries in the requirements.txt file using pip. Then, it will read the Procfile which specifies that the bot.py file is to be executed. 47 | 48 | 9. Go to your conversation with your Telegram bot on Telegram and type /start. The bot should be working now! 49 | 50 | Since you are using the free plan on heroku, the bot will sleep after 30 minutes of inactivity. So do expect the bot to take a few seconds to respond to your /start if you are using it more than 30 minutes after it was previously used. Other than that, the bot will respond almost instantaneously~ 51 | 52 | ## What to do if your Bot stops responding 53 | I’ve noticed the bot stops responding after about 24 hours of inactivity (because we are using the free version of Heroku), so if you want to “jolt” the bot awake, one way is to make a change to one of the files (eg. changing the python3 in the procfile to python and vice versa) and then committing the changes with the lines below: 54 | > git add . 55 | > git commit -m "changing python3 to python in Procfile" 56 | > git push heroku master 57 | 58 | You should see again see the messages about a Python app being detected and once it finishes executing, your bot should revive now! 59 | --------------------------------------------------------------------------------