Open MR-Tajeddin opened 1 year ago
Step | Description |
---|---|
1 | Create a bot on Telegram by talking to the BotFather and get your API token |
2 | Install the Python Telegram Bot library using pip |
3 | Import the necessary libraries in a new Python file |
4 | Create a new bot instance using your API token |
5 | Create a new updater instance and add a dispatcher to handle incoming messages |
6 | Define a function to handle incoming messages |
7 | Create a new message handler and add it to the dispatcher |
8 | Start the bot using the updater |
9 | Test the bot by sending a message to it on Telegram |
To create a Telegram bot using Python, follow these steps:
First, you need to create a bot on Telegram by talking to the BotFather. You can do this by searching for BotFather in the Telegram app and sending it a message "/start". Follow the prompts to create a new bot and get your API token.
Install the Python Telegram Bot library using pip. You can do this by running the following command in your terminal:
pip install python-telegram-bot
Create a new Python file and import the necessary libraries:
import telegram
from telegram.ext import Updater, CommandHandler, MessageHandler, Filters
Create a new bot instance using your API token:
bot = telegram.Bot(token='YOUR_API_TOKEN')
Create a new updater instance and add a dispatcher to handle incoming messages:
updater = Updater(token='YOUR_API_TOKEN', use_context=True)
dispatcher = updater.dispatcher
Define a function to handle incoming messages:
def echo(update, context):
context.bot.send_message(chat_id=update.effective_chat.id, text=update.message.text)
Create a new message handler and add it to the dispatcher:
echo_handler = MessageHandler(Filters.text & (~Filters.command), echo)
dispatcher.add_handler(echo_handler)
Start the bot using the updater:
updater.start_polling()
Your bot is now running and ready to receive messages. Test it out by sending a message to your bot on Telegram.
This is just a basic example of how to create a Telegram bot using Python. You can add more functionality by creating additional handlers and commands.
Hello please help me ....
I'd like to create a telegram bot that is used for a call center bot, and it's integrated with a spreadsheet to find the questions and answers of the FAQ for the customer.
I used the newest Python and I have already installed the telegram bot using PIP, but when I start the code, I get this problem:
Traceback (most recent call last): File "/Applications/bot_telegram/bot.py", line 6, in from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext ImportError: cannot import name 'Filters' from 'telegram.ext' (/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/telegram/ext/init.py)
and here is the code that I use:
import logging from datetime import datetime, time import gspread from oauth2client.service_account import ServiceAccountCredentials from telegram import Update, ReplyKeyboardMarkup, ReplyKeyboardRemove from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackContext
Configure logging logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
Initialize Google Sheets credentials scopes = ['https://www.googleapis.com/auth/spreadsheets'] credentials = ServiceAccountCredentials.from_json_keyfile_name('credentials.json', scopes)
Spreadsheet ID and FAQ worksheet spreadsheet_id = '113ertLcHiP73WBH0GRWyq9B19hcAis5atEtqif4xFn0' faq_sheet_name = 'FAQ Data' chat_sheet_name = 'Chat History'
Function to start the bot and greet the user def start(update: Update, context: CallbackContext): user = update.effective_user context.bot.send_message(chat_id=update.effective_chat.id, text=f"Hello {user.first_name}! Welcome to our customer service. Please provide your name.")
Function to handle user name submission def handle_name(update: Update, context: CallbackContext): user = update.effective_user name = update.message.text
context.user_data['name'] = name
context.bot.send_message(chat_id=update.effective_chat.id, text=f"Thank you, {name}! If you have any questions, please use the /faq command to see frequently asked questions.") Function to display the guide on how to use the bot def show_guide(update: Update, context: CallbackContext): guide_text = "How to use the bot:\n\n" "/faq - View frequently asked questions\n" "Send another message - Ask another question\n" "/guide - Display the guide on how to use the bot"
context.bot.send_message(chat_id=update.effective_chat.id, text=guide_text) Function to display FAQ questions and answers def faq(update: Update, context: CallbackContext):
gc = gspread.authorize(credentials) sheet = gc.open_by_key(spreadsheet_id).worksheet(faq_sheet_name)
faq_data = sheet.get_all_records()
faq_text = "Frequently Asked Questions:\n\n" for data in faq_data: faq_text += f"Q: {data['Question']}\n" faq_text += f"A: {data['Answer']}\n\n"
context.bot.send_message(chat_id=update.effective_chat.id, text=faq_text) Function to handle user messages def handle_message(update: Update, context: CallbackContext): user = update.effective_user message = update.message.text
gc = gspread.authorize(credentials) sheet = gc.open_by_key(spreadsheet_id).worksheet(chat_sheet_name)
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") chat_data = [timestamp, user.id, message] sheet.append_row(chat_data)
context.bot.send_message(chat_id=update.effective_chat.id, text="Thank you for your question! We will respond shortly.") Function to check the live chat time def check_live_chat(context: CallbackContext): current_time = datetime.now().time() live_chat_start_time = time(8, 0) # Live chat start time (8 AM) live_chat_end_time = time(17, 0) # Live chat end time (5 PM)
if live_chat_start_time <= current_time <= live_chat_end_time: admin_chat_id = '@inshamid' # Replace with the Telegram admin chat ID context.bot.send_message(chat_id=admin_chat_id, text="New question from a user.") Main function def main():
updater = Updater(token='YOUR_TELEGRAM_BOT_TOKEN', use_context=True) dispatcher = updater.dispatcher
start_handler = CommandHandler('start', start) dispatcher.add_handler(start_handler)
name_handler = MessageHandler(Filters.text & ~Filters.command, handle_name) dispatcher.add_handler(name_handler)
faq_handler = CommandHandler('faq', faq) dispatcher.add_handler(faq_handler)
message_handler = MessageHandler(Filters.text & ~Filters.command, handle_message) dispatcher.add_handler(message_handler)
guide_handler = CommandHandler('guide', show_guide) dispatcher.add_handler(guide_handler)
updater.job_queue.run_repeating(check_live_chat, interval=60, first=0)
updater.start_polling() updater.idle() if name == 'main': main()