Introduction
As we all know, our team has been working on core Telegram bots, providing free services to its members, families, and assisting developers with technical issues and various tasks. Now, as promised earlier, we are thrilled to announce that we are starting tutorial classes to share our skills with users who have little or no knowledge but are interested in learning.
Our Schedule 🗓
1. Python Telegram Bot Basics
- Estimated time: 6 weeks
2. Web Development Basics
- Estimated time: 8 weeks
3. Python Publishing Package
- Estimated time: 4 weeks
4. Python Telegram Bot Advanced
- Estimated time: 4 weeks
5. Python Telegram Bot Expert
- Estimated time: 5 weeks
6. Python Telegram Bot Certification
- Estimated time: 1 week
And more.
This is how we will spend the summer. It's important to note that we will start from scratch, assuming no prior knowledge on your part, so everyone can easily follow the tutorials. Additionally, translations will be available for you to enjoy the content in your preferred language.
You will prove yourself as a skilled coder!
@neuraltutor
As we all know, our team has been working on core Telegram bots, providing free services to its members, families, and assisting developers with technical issues and various tasks. Now, as promised earlier, we are thrilled to announce that we are starting tutorial classes to share our skills with users who have little or no knowledge but are interested in learning.
Our Schedule 🗓
1. Python Telegram Bot Basics
- Estimated time: 6 weeks
2. Web Development Basics
- Estimated time: 8 weeks
3. Python Publishing Package
- Estimated time: 4 weeks
4. Python Telegram Bot Advanced
- Estimated time: 4 weeks
5. Python Telegram Bot Expert
- Estimated time: 5 weeks
6. Python Telegram Bot Certification
- Estimated time: 1 week
And more.
This is how we will spend the summer. It's important to note that we will start from scratch, assuming no prior knowledge on your part, so everyone can easily follow the tutorials. Additionally, translations will be available for you to enjoy the content in your preferred language.
You will prove yourself as a skilled coder!
@neuraltutor
🔥7🥰1
Hello Everyone👋,
At the beginning of our tutorial, we've decided to teach you the basics of Python Telegram Bot.
By the end of this course, you will have a good understanding of:
●Basic HTTP requests
●Talking with Telegram API
●Developing Easier & A little bit advanced Bots
●Much more!
So, if you have a vision to become a professional developer, This is the right place for you.
What are prerequisites?
Well, one thing you need to know is that you should have a basic python knowledge.
And don't worry about Computer, we provide you code editors for mobile & tablets.
Are you excited?😍
😎Wonderful, The course will be started🔥
✨Get Ready!✨
And Things to Notice you can share for your freinds and even in your channels by giving us credit but if you refused to give and continued to kang,we will obliged to restrict content sharing
@neuraltutor
At the beginning of our tutorial, we've decided to teach you the basics of Python Telegram Bot.
By the end of this course, you will have a good understanding of:
●Basic HTTP requests
●Talking with Telegram API
●Developing Easier & A little bit advanced Bots
●Much more!
So, if you have a vision to become a professional developer, This is the right place for you.
What are prerequisites?
Well, one thing you need to know is that you should have a basic python knowledge.
And don't worry about Computer, we provide you code editors for mobile & tablets.
Are you excited?😍
😎Wonderful, The course will be started🔥
✨Get Ready!✨
And Things to Notice you can share for your freinds and even in your channels by giving us credit but if you refused to give and continued to kang,we will obliged to restrict content sharing
@neuraltutor
👍2🔥2
#bot
Python Telegram Bot 🤖
Requirements
before getting started to learn Python Telegram Bot development, we have to see what's required and needed
1 little Python knowledge
2 to have a stable device pc or android
3 Telegram account
if you don't have the first one no matter you can learn from the Internet or any other source for quick. here are the best I recommend for you
sololearn
w3shools -> w3shools.com
freecodecamp
programming hero
you can get all of them in playstore
next, we will set up our coding environment be with us👍
@neuraltutor 😊
Python Telegram Bot 🤖
Requirements
before getting started to learn Python Telegram Bot development, we have to see what's required and needed
1 little Python knowledge
2 to have a stable device pc or android
3 Telegram account
if you don't have the first one no matter you can learn from the Internet or any other source for quick. here are the best I recommend for you
sololearn
w3shools -> w3shools.com
freecodecamp
programming hero
you can get all of them in playstore
next, we will set up our coding environment be with us👍
@neuraltutor 😊
❤3👍1
#bot
The Starting Point
1 Setting Environment
before we dive into coding, we have to set up our coding lab and install some required packages
For Pc you can use VS Code
Download link 》 https://code.visualstudio.com/download
, for android device there is Pydroid and Termux which i am using for the tutorial
Pydroid Link 》 https://t.me/neuraltutor/34
Termux Link 》 https://f-droid.org/repo/com.termux_118.apk
Next we will see installing packages
@neuraltutor
The Starting Point
1 Setting Environment
before we dive into coding, we have to set up our coding lab and install some required packages
For Pc you can use VS Code
Download link 》 https://code.visualstudio.com/download
, for android device there is Pydroid and Termux which i am using for the tutorial
Pydroid Link 》 https://t.me/neuraltutor/34
Termux Link 》 https://f-droid.org/repo/com.termux_118.apk
Next we will see installing packages
@neuraltutor
👍3
#bot #pyrogram
installing packages 📦
assuming that you have installed Python extension and Python interpreter in VS code
•for termux android use below command to install python
1
2
3
if you faced any difficulty, you can Google or ask in the comments below
there are cool🙂 telegram bot libraries, but for this tutorial, we have chosen pyrogram, which is mtproto and usefull with making userbots [next time we will see all others💁♂]
use the below command to install it
we will see how to interact with bot in the next post don't forget to react and share😉
@neuraltutor 😊
installing packages 📦
assuming that you have installed Python extension and Python interpreter in VS code
•for termux android use below command to install python
1
pkg update 2
pkg upgrade 3
pkg install python if you faced any difficulty, you can Google or ask in the comments below
there are cool🙂 telegram bot libraries, but for this tutorial, we have chosen pyrogram, which is mtproto and usefull with making userbots [next time we will see all others💁♂]
use the below command to install it
pip install pyrogram we will see how to interact with bot in the next post don't forget to react and share😉
@neuraltutor 😊
👍3🔥2🎉1
#bot #pyrogram
Getting Access Token🤖
first, let's gain bot token
1. go to @botfather [bots call it dady😉]
2. type /newbot
3. You'll be asked a name for your new bot. You can use whatever you want [except the name neural😌]
4. Next, you'll be asked a username for your new bot. the username must end with suffix -bot, and it must be unique .You can include underscore(_) and numbers
5. if you succeed ✨️ well, you'll get a congra message from botfather, which contained your bot token
6. (optional) then type /mybots for more effective decoration to your bot, you can set profile picture ,description, about ,commands....etc for your bot
😊as God composed Adam's body from mud , we have also arranged our bot' body from commands😎
next time, we will give breath [life] to our bot
@neuraltutor 😊
Getting Access Token🤖
first, let's gain bot token
1. go to @botfather [
2. type /newbot
3. You'll be asked a name for your new bot. You can use whatever you want [except the name neural😌]
4. Next, you'll be asked a username for your new bot. the username must end with suffix -bot, and it must be unique .You can include underscore(_) and numbers
5. if you succeed ✨️ well, you'll get a congra message from botfather, which contained your bot token
6. (optional) then type /mybots for more effective decoration to your bot, you can set profile picture ,description, about ,commands....etc for your bot
😊as God composed Adam's body from mud , we have also arranged our bot' body from commands😎
next time, we will give breath [life] to our bot
@neuraltutor 😊
😁4👍3❤1🔥1
#bot #pyrogram
Let's give life to our Bot❤️
before preceeding to code, we have forgotten something required on the previous post. Those are Api ID and Api HASH, which are required for mtproto libraries. you can get both of them from my.telegram.org just login and create one app there (for the tutor, we will use mine😊 )
Code
whenever we send something to the including message , media ...etc it should give us response in this situation it will response "i am alive"
Code
next we will see all Client object parameters🙌
@neuraltutor 😊
Let's give life to our Bot❤️
before preceeding to code, we have forgotten something required on the previous post. Those are Api ID and Api HASH, which are required for mtproto libraries. you can get both of them from my.telegram.org just login and create one app there (for the tutor, we will use mine😊 )
Code
BOT_TOKEN = your bot token
#have mine here😊 still you can use yours
API_ID = 9583161
API_HASH = "aecf9e2b7c655c4f916564ab6d598a73"
#first we will import Client class from pyrogram module
from pyrogram import Client
bot = Client ( "neural tutor ",
api_id = API_ID,
api_hash = API_HASH ,
bot_token = BOT_TOKEN
)
bot.start()
print(bot.get_me()) #this code will print about the bot including id, status , profile ,username ...
2 let us make it responsive whenever we send something to the including message , media ...etc it should give us response in this situation it will response "i am alive"
Code
BOT_TOKEN = bot token #string
#have mine here😊
API_ID = 9583161
API_HASH = "aecf9e2b7c655c4f916564ab6d598a73"
bot = Client ( "neural tutor ",
api_id = API_ID,
api_hash = API_HASH ,
bot_token = BOT_TOKEN
)
#next we have message handler here ,it can be triggered whenever there is incoming messages
@bot.on_message()
#we created a function to handle or to give response for what's received
def response(bot ,message ):
#we can do whatever we want here
#for now i am replying with this message
message.reply('i am alive')
bot.run()
#now our bot is alive until we hit ctrl + Cnext we will see all Client object parameters🙌
@neuraltutor 😊
👍4🔥1🤩1🫡1
#bot #pyrogram
Deep inside Client 🧍♀️
as we mentioned earlier today we will see all Client object parameters
let's get started😋
The client object is the main means for interacting with Telegram
Client takes the below parameters some of them are required and some are optional
Parameters:
name (str) – A name for the client, e.g.: “neural tutor”.
api_id (int | optional) – The api_id part of the Telegram API key, as integer E.g.: 12345
api_hash (str, optional) – The api_hash part of the Telegram API key, as string. E.g.: “0123456789abcdef0123456789abcdef”.
app_version (str, optional) – Application version. Defaults to “Pyrogram x.y.z”.
device_model (str, optional) – Device model. Defaults to platform.python_implementation() + “ “ + platform.python_version().
system_version (str, optional) – Operating System version. Defaults to platform.system() + “ “ + platform.release().
lang_code (str, optional) – Code of the language used on the client, in ISO 639-1 standard. Defaults to “en”.
ipv6 (bool, optional) – Pass True to connect to Telegram using IPv6. Defaults to False (IPv4).
proxy (dict, optional) – The Proxy settings as dict. E.g.: dict(scheme=”socks5”, hostname=”11.22.33.44”, port=1234, username=”user”, password=”pass”). The username and password can be omitted if the proxy doesn’t require authorization.
test_mode (bool, optional) – Enable or disable login to the test servers. Only applicable for new sessions and will be ignored in case previously created sessions are loaded. Defaults to False.
bot_token (str, optional) – Pass the Bot API token to create a bot session, e.g.: “123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11” Only applicable for new sessions.
session_string (str, optional) – Pass a session string to load the session in-memory. Implies in_memory=True.
in_memory (bool, optional) – Pass True to start an in-memory session that will be discarded as soon as the client stops. In order to reconnect again using an in-memory session without having to login again, you can use export_session_string() before stopping the client to get a session string you can pass to the session_string parameter. Defaults to False.
phone_number (str, optional) – Pass the phone number as string (with the Country Code prefix included) to avoid entering it manually. Only applicable for new sessions.
phone_code (str, optional) – Pass the phone code as string (for test numbers only) to avoid entering it manually. Only applicable for new sessions.
password (str, optional) – Pass the Two-Step Verification password as string (if required) to avoid entering it manually. Only applicable for new sessions.
workers (int, optional) – Number of maximum concurrent workers for handling incoming updates. Defaults to min(32, os.cpu_count() + 4).
workdir (str, optional) – Define a custom working directory. The working directory is the location in the filesystem where Pyrogram will store the session files. Defaults to the parent directory of the main script.
plugins (dict, optional) – Smart Plugins settings as dict, e.g.: dict(root=”plugins”).
parse_mode (ParseMode, optional) – Set the global parse mode of the client. By default, texts are parsed using both Markdown and HTML styles. You can combine both syntaxes together.
no_updates (bool, optional) – Pass True to disable incoming updates. When updates are disabled the client can’t receive messages or other updates. Useful for batch programs that don’t need to deal with updates. Defaults to False (updates enabled and received).
takeout (bool, optional) – Pass True to let the client use a takeout session instead of a normal one, implies no_updates=True. Useful for exporting Telegram data. Methods invoked inside a takeout session (such as get_chat_history, download_media, …) are less prone to throw FloodWait exceptions. Only available for users, bots will ignore this parameter. Defaults to False (normal session).
Deep inside Client 🧍♀️
as we mentioned earlier today we will see all Client object parameters
let's get started😋
The client object is the main means for interacting with Telegram
Client takes the below parameters some of them are required and some are optional
Parameters:
name (str) – A name for the client, e.g.: “neural tutor”.
api_id (int | optional) – The api_id part of the Telegram API key, as integer E.g.: 12345
api_hash (str, optional) – The api_hash part of the Telegram API key, as string. E.g.: “0123456789abcdef0123456789abcdef”.
app_version (str, optional) – Application version. Defaults to “Pyrogram x.y.z”.
device_model (str, optional) – Device model. Defaults to platform.python_implementation() + “ “ + platform.python_version().
system_version (str, optional) – Operating System version. Defaults to platform.system() + “ “ + platform.release().
lang_code (str, optional) – Code of the language used on the client, in ISO 639-1 standard. Defaults to “en”.
ipv6 (bool, optional) – Pass True to connect to Telegram using IPv6. Defaults to False (IPv4).
proxy (dict, optional) – The Proxy settings as dict. E.g.: dict(scheme=”socks5”, hostname=”11.22.33.44”, port=1234, username=”user”, password=”pass”). The username and password can be omitted if the proxy doesn’t require authorization.
test_mode (bool, optional) – Enable or disable login to the test servers. Only applicable for new sessions and will be ignored in case previously created sessions are loaded. Defaults to False.
bot_token (str, optional) – Pass the Bot API token to create a bot session, e.g.: “123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11” Only applicable for new sessions.
session_string (str, optional) – Pass a session string to load the session in-memory. Implies in_memory=True.
in_memory (bool, optional) – Pass True to start an in-memory session that will be discarded as soon as the client stops. In order to reconnect again using an in-memory session without having to login again, you can use export_session_string() before stopping the client to get a session string you can pass to the session_string parameter. Defaults to False.
phone_number (str, optional) – Pass the phone number as string (with the Country Code prefix included) to avoid entering it manually. Only applicable for new sessions.
phone_code (str, optional) – Pass the phone code as string (for test numbers only) to avoid entering it manually. Only applicable for new sessions.
password (str, optional) – Pass the Two-Step Verification password as string (if required) to avoid entering it manually. Only applicable for new sessions.
workers (int, optional) – Number of maximum concurrent workers for handling incoming updates. Defaults to min(32, os.cpu_count() + 4).
workdir (str, optional) – Define a custom working directory. The working directory is the location in the filesystem where Pyrogram will store the session files. Defaults to the parent directory of the main script.
plugins (dict, optional) – Smart Plugins settings as dict, e.g.: dict(root=”plugins”).
parse_mode (ParseMode, optional) – Set the global parse mode of the client. By default, texts are parsed using both Markdown and HTML styles. You can combine both syntaxes together.
no_updates (bool, optional) – Pass True to disable incoming updates. When updates are disabled the client can’t receive messages or other updates. Useful for batch programs that don’t need to deal with updates. Defaults to False (updates enabled and received).
takeout (bool, optional) – Pass True to let the client use a takeout session instead of a normal one, implies no_updates=True. Useful for exporting Telegram data. Methods invoked inside a takeout session (such as get_chat_history, download_media, …) are less prone to throw FloodWait exceptions. Only available for users, bots will ignore this parameter. Defaults to False (normal session).
👍3👏2
sleep_threshold (int, optional) – Set a sleep threshold for flood wait exceptions happening globally in this client instance, below which any request that raises a flood wait will be automatically invoked again after sleeping for the required amount of time. Flood wait exceptions requiring higher waiting times will be raised. Defaults to 10 seconds.
hide_password (bool, optional) – Pass True to hide the password when typing it during the login. Defaults to False, because getpass (the library used) is known to be problematic in some terminal environments.
max_concurrent_transmissions (bool, optional) – Set the maximum amount of concurrent transmissions (uploads & downloads). A value that is too high may result in network related issues. Defaults to 1.
let's see some of them in example
we can use all of them depending on what task we want to perform
next we will see something further share for your friends👬
@neuraltutor 😊
hide_password (bool, optional) – Pass True to hide the password when typing it during the login. Defaults to False, because getpass (the library used) is known to be problematic in some terminal environments.
max_concurrent_transmissions (bool, optional) – Set the maximum amount of concurrent transmissions (uploads & downloads). A value that is too high may result in network related issues. Defaults to 1.
let's see some of them in example
from pyrogram import Client
bot = Client ( "neural tutor ",
api_id = 123456,
api_hash = 'qwertyyozccvnfdahkkalwqAedkdjfkaxbcnmewk' ,
lang_code = 'en'
ipv6 = True,
test_mode = True,
session_string = 'skskmdmdmdmdzncncnxkekekekke', #mostly used to make userbots
in_memory = True ,
sleep_threshold = 30
#such like that
)
we can use all of them depending on what task we want to perform
next we will see something further share for your friends👬
@neuraltutor 😊
🔥3👏2
#terminal #termux #bash
How to Use terminal
we have been busy making some stuffs @neuralp , we say sorry for the missing daily post.
today we will explore the top commands of the bash programming language. Bash, short for "Bourne Again SHell," is a popular Unix shell and command language interpreter. It provides a powerful and flexible environment for scripting and automating tasks in a Unix-like operating system.
on android, we use termux , for Windows users , open cmd panel ( winkey + R 》 type cmd + enter )
Let's dive into the code and see top commands of bash:
#!/bin/bash
Command 1: echo
echo "Hello, World!"
Command 2: ls
ls -l
Command 3: cd
cd /path/to/directory
Command 4: pwd
pwd
Command 5: mkdir
mkdir new_directory
Command 6: rm
rm file.txt
Command 7: cp
cp file.txt new_file.txt
Command 8: mv
mv file.txt new_directory/
Command 9: grep
grep "pattern" file.txt
Command 10: chmod
chmod +x script.sh
Now, let's explain each command in detail:
1. echo: The echo command is used to display a line of text or a variable value on the standard output. In the code example, it prints "Hello, World!" to the console.
2. ls: The ls command lists the files and directories in the current directory. The -l option displays detailed information, such as permissions, owner, size, and modification time.
3. cd: The cd command is used to change the current directory. In the code example, it changes the directory to "/path/to/directory".
4. pwd: The pwd command prints the current working directory.
5. mkdir: The mkdir command creates a new directory. In the code example, it creates a directory named "new_directory".
6. rm: The rm command is used to remove files and directories. In the code example, it removes a file named "file.txt".
7. cp: The cp command copies files and directories. In the code example, it copies a file named "file.txt" to "new_file.txt".
8. mv: The mv command moves or renames files and directories. In the code example, it moves a file named "file.txt" to the "new_directory".
9. grep: The grep command searches for a specified pattern in a file or multiple files. In the code example, it searches for the pattern "pattern" in the file "file.txt".
10. chmod: The chmod command changes the permissions of a file or directory. In the code example, it adds executable permissions to a script named "script.sh".
By utilizing these top commands of bash, you can efficiently navigate the file system, manipulate files and directories, and perform various text processing operations , also it is required to run and build our future bot
Please practice all of them in your terminal to master them✊
@neuraltutor 😊
How to Use terminal
we have been busy making some stuffs @neuralp , we say sorry for the missing daily post.
today we will explore the top commands of the bash programming language. Bash, short for "Bourne Again SHell," is a popular Unix shell and command language interpreter. It provides a powerful and flexible environment for scripting and automating tasks in a Unix-like operating system.
on android, we use termux , for Windows users , open cmd panel ( winkey + R 》 type cmd + enter )
Let's dive into the code and see top commands of bash:
#!/bin/bash
Command 1: echo
echo "Hello, World!"
Command 2: ls
ls -l
Command 3: cd
cd /path/to/directory
Command 4: pwd
pwd
Command 5: mkdir
mkdir new_directory
Command 6: rm
rm file.txt
Command 7: cp
cp file.txt new_file.txt
Command 8: mv
mv file.txt new_directory/
Command 9: grep
grep "pattern" file.txt
Command 10: chmod
chmod +x script.sh
Now, let's explain each command in detail:
1. echo: The echo command is used to display a line of text or a variable value on the standard output. In the code example, it prints "Hello, World!" to the console.
2. ls: The ls command lists the files and directories in the current directory. The -l option displays detailed information, such as permissions, owner, size, and modification time.
3. cd: The cd command is used to change the current directory. In the code example, it changes the directory to "/path/to/directory".
4. pwd: The pwd command prints the current working directory.
5. mkdir: The mkdir command creates a new directory. In the code example, it creates a directory named "new_directory".
6. rm: The rm command is used to remove files and directories. In the code example, it removes a file named "file.txt".
7. cp: The cp command copies files and directories. In the code example, it copies a file named "file.txt" to "new_file.txt".
8. mv: The mv command moves or renames files and directories. In the code example, it moves a file named "file.txt" to the "new_directory".
9. grep: The grep command searches for a specified pattern in a file or multiple files. In the code example, it searches for the pattern "pattern" in the file "file.txt".
10. chmod: The chmod command changes the permissions of a file or directory. In the code example, it adds executable permissions to a script named "script.sh".
By utilizing these top commands of bash, you can efficiently navigate the file system, manipulate files and directories, and perform various text processing operations , also it is required to run and build our future bot
Please practice all of them in your terminal to master them✊
@neuraltutor 😊
👏3🔥2👍1
#telegram_bot #pyrogram
⭐️ Basics of building Telegram Bots🤖
👆 Hello Everyone, In Today's tutorial we are gonna build simple telegram bot in python using pyrogram library.
In the previous tutorial we've have some basic right, now its time to move on some a little bit advanced bots. Lets go!
A bot which we are gonna build teach you some methods of the library and the following:
●Handling events
●Making KeyboardButtons
>There are two types of buttons: InlineKeyboardButton & ReplyKeyboardMarkup
●Sending Photos
●Deleting messages
And such things.
Let's begin by creating simple boilerplate for our bot:
Here is our code:
In the previous tutorial we've have some basic right, now its time to move on some a little bit advanced bots. Lets go!
A bot which we are gonna build teach you some methods of the library and the following:
●Handling events
●Making KeyboardButtons
>There are two types of buttons: InlineKeyboardButton & ReplyKeyboardMarkup
●Sending Photos
●Deleting messages
And such things.
Let's begin by creating simple boilerplate for our bot:
from pyrogram import Client, filters
api_id = "your API_ID"
api_hash = "your API_HASH"
bot_token = "your BOT_TOKEN"
app = Client("neural_bot", api_id=api_id, api_hash=api_hash, bot_token=bot_token)
@app.on_message(filters.command("start"))
async def start(_, message):
await message.reply("Hey")
print("Bot has been started!")
app.run()
Make sure to replace with your own actual API_ID & API_HASH & BOT_TOKEN!Here is our code:
from pyrogram import Client, filters
from pyrogram.types import ReplyKeyboardMarkup, KeyboardButton, InlineKeyboardMarkup, InlineKeyboardButton, ReplyKeyboardRemove
import random
#user random module to select items randomly
api_id = "your API_ID"
api_hash = "your API_HASH"
bot_token = "your BOT_TOKEN"
app = Client("neural_bot", api_id=api_id, api_hash=api_hash, bot_token=bot_token)
#ReplyKeyboardMarkup
keyboard = ReplyKeyboardMarkup([
[KeyboardButton(text="Send Photo"), KeyboardButton(text="Send Poll")],
[KeyboardButton(text="Random Emoji"), KeyboardButton(text="Change Keyboard")]
], resize_keyboard=False)
#pass resize_keyboard = True if you wanna make it smaller
#InlineKeyboardMarkup
inline_keyboard = InlineKeyboardMarkup([
[InlineKeyboardButton(text="Send Photo", callback_data="send_photo"), InlineKeyboardButton(text="Send Poll", callback_data="send_poll")],
[InlineKeyboardButton(text="Random Emoji", callback_data="random_emoji"), InlineKeyboardButton(text="Change Keyboard", callback_data="change_keyboard")]
])
#Here you would probably notice that we have passed callback_data parameter, this is because we use this callback_data to handle when specific button is clicked
#bear in mind you can make Keyboards dynamically.
@app.on_message(filters.command("start"))
async def start(_, message):
#sending keyboard with reply_markup parameter
await message.reply("Welcome to My Telegram bot.\nChoose Keyboard:", reply_markup=keyboard)
"""once we've keyboard to user, now we have to respond when user clicks one of the buttons, so to do this we use on_message() handler"""
"""To receive only text use, we user filters.text parameter, feel free to use other parameters: filters.photo, filters.document etc."""
emoji = ["😁", "😎", "😉", "🤗","😊"]
@app.on_message(filters.text)
async def handle_all_msg(_, message):
"""from message object we can extract text as: message.text, Great, Lets continue."""
if message.text == "Send Photo":
photo_id = random.randint(300, 800)
photo_url = f"https://picsum.photos/{photo_id}"
#we are sending photo from a website, once we have photo, we can send it to user
await app.send_photo(message.chat.id, photo_url, caption="This is my caption!")
elif message.text == "Random Emoji":
emoji_to_be_sent = random.choice(emoji)
await app.send_message(message.chat.id, emoji_to_be_sent)
elif message.text == "Send Poll":
await app.send_poll(message.chat.id, question="What do you like?", options=["Mango","Apple","Both"])
elif message.text == "Change Keyboard":
#Now lets remove ReplyKeyboardMarkup and send InlineKeyboardMarkup
await message.reply("Keyboard has been changed!", reply_markup=ReplyKeyboardRemove())
await message.reply("Choose options:", reply_markup=inline_keyboard)
""""
So far, we have handled all our buttons events, Now lets handle InlineKeyboardButtons using on_callback_query() handler
"""Please open Telegram to view this post
VIEW IN TELEGRAM
🫡2👏1
@app.on_callback_query()
async def answer_callback(_, callback):
print(callback)
await app.answer_callback_query(callback.id, "You have clicked InlineKeyboardButton!", show_alert=True)
if callback.data == "change_keyboard":
await app.delete_messages(callback.from_user.id, callback.message.id)
await app.send_message(callback.from_user.id, "Choose Keyboard", reply_markup=keyboard)
#see what callback contains, we will show you how to handle this in the next tutorial
print("Bot has been started!")
app.run()That's it. Run the code, again make sure to replace Client parameters with your own actual API_ID & API_HASH & BOT_TOKEN.
Please open Telegram to view this post
VIEW IN TELEGRAM
👍5🥰3