I am really new to python and I want my bot answers only limit users by their username.
I am trying to code this feature, but my bot send only one message "Not authorized".
What is wrong?
number_list.append(choice)
if update.effective_user.username not in ["username"]:
query.edit_message_text(text="Not authorized")
return
You can use telebot api
import telebot
bot = telebot.TeleBot("TOKEN")
username = ["USERNAME"]
#bot.message_handler(content_types=["text"])
def default_test(message):
if message.from_user.username not in username:
bot.send_message(message.chat.id, "Not authorized")
else:
bot.send_message(message.chat.id, "Authorized")
bot.polling(none_stop=True)
Related
Im trying to write a script in python that listen "first reply" of a bot and then exits. So, I create a client instance and then send a msg to Bot and now I want to record only first reply of bot (upcoming replies can ignored), and save bot reply to Reply variable. Now how to exit from listener mode so that I can do other stuffs after getting reply. I tried client.disconnect() and client.disconnected() but now working or maybe I don't know proper use of these method. I'm new to telethon APIs.
When I run this script, a msg from my telegram is sent to
bot(BotFather) and then bot send a reply
Reply from bot father
I can help you create and manage Telegram bots. If you're new to the
Bot API, please see the manual (https://core.telegram.org/bots).
You can control me by sending these commands:
/newbot - create a new bot /mybots - edit your bots [beta]
Edit Bots /setname - change a bot's name /setdescription - change bot
description /setabouttext - change bot about info /setuserpic - change
bot profile photo /setcommands - change the list of commands
/deletebot - delete a bot
Bot Settings /token - generate authorization token /revoke - revoke
bot access token /setinline - toggle inline mode
(https://core.telegram.org/bots/inline) /setinlinegeo - toggle inline
location requests
(https://core.telegram.org/bots/inline#location-based-results)
/setinlinefeedback - change inline feedback
(https://core.telegram.org/bots/inline#collecting-feedback) settings
/setjoingroups - can your bot be added to groups? /setprivacy - toggle
privacy mode (https://core.telegram.org/bots#privacy-mode) in groups
Games /mygames - edit your games
(https://core.telegram.org/bots/games) [beta] /newgame - create a new
game (https://core.telegram.org/bots/games) /listgames - get a list of
your games /editgame - edit a game /deletegame - delete an existing
game
and this reply got assigned in Reply variable
but my scripts
still listening for other upcoming events. is there any method from
which I can close this connection.
import random
import traceback
import configparser
from telethon import TelegramClient, events, sync
from telethon.errors import SessionPasswordNeededError
from telethon.errors.rpcerrorlist import PeerFloodError
from telethon.tl.functions.channels import InviteToChannelRequest
from telethon.tl.functions.messages import GetDialogsRequest,GetHistoryRequest
from telethon.tl.types import InputPeerEmpty, InputPeerChannel, InputPeerUser, PeerChannel
api_id = #Api_ID
api_hash = #Api_Hash
phone = #session
client = TelegramClient(phone, api_id, api_hash)
Reply = ' '
#client.on(events.NewMessage(chats='https://t.me/BotFather'))
async def NewMessageListener(event):
Reply = event.message.message
with client:
client.send_message("https://t.me/BotFather", "/start")
client.run_until_disconnected()
# Disconnect client to stop run_until_disconnected()
# Do other stuff!!!
I don't understand what you trying to achieve here but you can disconnect the client using disconnect method
from telethon import TelegramClient, events
api_id = #Api_ID
api_hash = #Api_Hash
phone = #session
client = TelegramClient(phone, api_id, api_hash)
Reply = ' '
#client.on(events.NewMessage(chats='https://t.me/BotFather'))
async def newMessageListener(event):
reply = event.message.message
# do stuff with reply then close the client
await client.disconnect()
async def main():
async with client:
await client.send_message("https://t.me/BotFather", "/start")
await client.run_until_disconnected()
I was building a WhatsApp bot using Twilio and Flask. So what should I do to make my WhatsApp bot wait for user reply and then execute the rest of the code. For example, my bot asks the user yes or no, the bot should wait for a reply, and based on the message received execute the rest of the code.
msg = request.form.get('Body')
resp = MessagingResponse()
msg = resp.message()
msg.body('Yes or No')
return str(resp)
{Wait For Reply}
if msg == 'yes':
do something
else:
do else
I am a begginer at Python.Please Help me .Thanks in advance
I'm programming a Telegram bot in python with the python-telegram-bot library for python3.x It's a bot for private use only (me and some relatives), so I would like to prevent other users from using it. My idea is to create a list of authorized user IDs and the bot must not answer to messages received from users not in the list. How can I do that?
Edit: I'm quite a newbie to both python and python-telegram-bot. I'd appreciate a code snippet as example if possible =).
I found a solution from the official wiki of the library which uses a decorator. Code:
from functools import wraps
LIST_OF_ADMINS = [12345678, 87654321] # List of user_id of authorized users
def restricted(func):
#wraps(func)
def wrapped(update, context, *args, **kwargs):
user_id = update.effective_user.id
if user_id not in LIST_OF_ADMINS:
print("Unauthorized access denied for {}.".format(user_id))
return
return func(update, context, *args, **kwargs)
return wrapped
#restricted
def my_handler(update, context):
pass # only accessible if `user_id` is in `LIST_OF_ADMINS`.
I just #restricted each function.
You can also create a custom Handler to restrict message handlers being executed.
import telegram
from telegram import Update
from telegram.ext import Handler
admin_ids = [123456, 456789, 1231515]
class AdminHandler(Handler):
def __init__(self):
super().__init__(self.cb)
def cb(self, update: telegram.Update, context):
update.message.reply_text('Unauthorized access')
def check_update(self, update: telegram.update.Update):
if update.message is None or update.message.from_user.id not in admin_ids:
return True
return False
Just make sure to register AdminHandler as the first handler:
dispatcher.add_handler(AdminHandler())
Now every update (or message) that is received by the Bot will be rejected if it's not from an authorized user (admin_ids).
Using the chat id. Create a little list with the chat id's you want to allow, you can ignore the rest.
A link to the docs where you can find the specifics
https://python-telegram-bot.readthedocs.io/en/stable/telegram.chat.html
admins=[123456,456789]
if update.message.from_user.id in admins:
update.message.reply_text('You are authorized to use this BOT!')
else:
update.message.reply_text('You are not authorized to access this BOT')
...
admins = ['123456', '565825', '2514588']
user = message.from_user.id
if user in admins:
...
You can use telegram.ext.filters.User.
Small example below
from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler
from telegram.ext.filters import User
ALLOWED_IDS = [123456, 78910]
TOKEN = 'TOKEN'
async def start(update: Update, context):
await context.bot.send_message(chat_id=update.effective_chat.id, text="Wow! Admin found!")
if __name__ == '__main__':
application = ApplicationBuilder().token(TOKEN).build()
start_handler = CommandHandler('start', start, filters=User(ALLOWED_IDS))
application.add_handler(start_handler)
application.run_polling()
I am using the Telethon library for python. How can I change Telegram channel name? Couldn't find this in documentation.
For now, you have to use Telethon's raw API. If we search for "edit title" we will find channels.editTitle. Such page has the following automatically-generated example:
from telethon.sync import TelegramClient
from telethon import functions, types
with TelegramClient(name, api_id, api_hash) as client:
result = client(functions.channels.EditTitleRequest(
channel='username',
title='My awesome title'
))
print(result.stringify())
If you meant the username, channels.updateUsername is the right one:
client(functions.channels.UpdateUsernameRequest(
channel='old username',
username='new username'
))
You can of course pass the channel ID or invite link instead of the username if it doesn't have one.
I'm trying to build a bot which automatically sends a message whenever there is an update in the latest news using python. Following is what I did.
companies = {
"name_1": {
"rss": "name_1 rss link",
"link": "name_1 link"
}
}
import feedparser as fp
import time, telebot
token = <TOKEN>
bot = telebot.TeleBot(token)
LIMIT = 1
while True:
def get_news():
count = 1
news = []
for company, value in companies.items():
count = 1
if 'rss' in value:
d = fp.parse(value['rss'])
for entry in d.entries:
if hasattr(entry, 'published'):
if count > LIMIT:
break
news.append(entry.link)
count = count + 1
return (news)
val = get_news()
time.sleep(10)
val2 = get_news()
try:
if val[0]!=val2[0]:
bot.send_message(chat_id= "Hardcoded chat_id", text=val2[0])
except Exception:
pass
How can I update my code so that the bot publishes the latest news to all the groups to which it is added?
I got the chat_id using:
bot.get_updates()[-1].message.chat.id
Any suggestions on how to automate this?
Using the python-telegram-bot api, you can send a message like this
bot.send_message(id, text='Message')
you need the "bot" and "id"
I keep these in a dictionary called "mybots" which I fill/update when people interact with the bot for the first time / or on later communication with the bot. It's possible to pickle this dictionary to keep it persistant.
mybots = {}
def start(bot, update):
"""Send a message when the command /start is issued."""
mybots[update.message.chat_id] = bot
update.message.reply_text('Hello{}!'.format(
update.effective_chat.first_name))
def send_later():
for id, bot in mybots.items():
bot.send_message(id, text='Beep!')
In short, you can use sendMessage() to send message to a specific group or user.
bot.sendMessage(chat_id=chat_id, text=msg)
the complete code,
import telegram
#token that can be generated talking with #BotFather on telegram
my_token = ''
def send(msg, chat_id, token=my_token):
"""
Send a message to a telegram user or group specified on chatId
chat_id must be a number!
"""
bot = telegram.Bot(token=token)
bot.sendMessage(chat_id=chat_id, text=msg)