Get Account Telegram bot telethon [duplicate] - python

How can I get telegram user_detail if know only the mobile number.
When a user signs_up to telegram, telegram returns an object which included user_id and access_hash.
So that if i need to send message to user, i will only need telegram user_id and hash to send message to that user.
client.send_message(InputPeerUser(u.id, u.access_hash), "hi")
Now for a users whose only number is provided how can i get his id and access_hash si that i can send message to user by telegram API

you should first add phone number to your contact list, the returned result from telegram will contain the ID and Access_hash:
contact = InputPhoneContact(client_id=0, phone=phone, first_name="", last_name="")
result = client(ImportContactsRequest([contact]))
usrDict = result.__dict__["users"]
if usrDict:
chatID = usrDict[0].__dict__["id"]
access_hash = usrDict[0].__dict__["access_hash"]

Related

Transfer Telegram channel ownership using pyrogram library

How to transfer channel ownership?
I want to transfer ownership of a Telegram channel using pyrogram.
There is a promote_chat_member method but it does not have an owner input parameter. There is also a pyrogram.raw.functions.channels.EditCreator method but I don't understand how to use it.
Try this in order to use the pyrogram.raw.functions.channels.EditCreator method
NOTES:
This operation must be done with an user account. It's necessary that you pass your phone number to the Client. (This operations can't be performed by bots)
The user must be a member of the channel. The code will promote the
user to Admin.
Get new_owner_id and channel_id using IDBot in Telegram (#username_to_id_bot). You'll need to send the username of the new owner and the join link of the channel to the bot.
Set a 2FA password in your account at least 1 week before running the
code (it's an API requirement)
Requirements
pip install pyrogram
pip install nest-asyncio
CODE
from pyrogram import Client
from pyrogram.raw.functions.channels import EditCreator
from pyrogram.raw.functions.account import GetPassword
import nest_asyncio
nest_asyncio.apply()
app = Client("app_name_you_like",api_id="your_api_id",api_hash="your_api_hash",phone_number="your_phone_number")
channel_id = channel_id #int -> enter your channel_id here
user_id = new_owner_id #int -> enter your new_owner_id here
async def make_owner():
await app.start()
channel_data = await app.resolve_peer(channel_id)
user_data = await app.resolve_peer(user_id)
password = await app.invoke(GetPassword())
#Make user Admin
await app.promote_chat_member(channel_id, user_id)
#Make user Owner
await app.invoke(EditCreator(channel=channel_data,user_id=user_data,password=password))
await app.stop()
app.run(make_owner())
Extra Notes:
If you don't have your Telegram API Credentials you can get them in this link
Here's a sample code how you can do it
from pyrogram import Client
# Creating Pyrogram client
app = Client("my_account")
app.start()
# replace the below channel_username with Channel you want to transfer ownership of
channel = app.get_chat("channel_username")
# Get the ID of the user whom you want to transfer
new_owner_id = 00000 # Replace 00000 wit the id of new owner
# Get the current owner ID of the channel
current_owner_id = channel.owner_id
# Transfer Ownsership
app.edit_administrator(
chat_id=channel.id,
user_id=new_owner_id,
is_owner=True,
can_change_info=True,
can_invite_users=True,
can_delete_messages=True,
can_restrict_members=True,
can_pin_messages=True,
can_promote_members=True
)
# Revoke the old owner's admin permissions
app.edit_administrator(
chat_id=channel.id,
user_id=current_owner_id,
is_owner=False,
can_change_info=False,
can_invite_users=False,
can_delete_messages=False,
can_restrict_members=False,
can_pin_messages=False,
can_promote_members=False
)
# Logout
app.stop()

python telegrambot store chat id

I am wondering how I could store/read out a user chat ID to later send them messages.
Example would be, that the user is adding my telegram bot and sends him a message.
Later on in my program at some point, when a sepcific situation occurs, I want to send a message to the specific user.
For a simple example I have this code:
a=1
b=2
if a > b:
# at this point python should send a message to a user via telegram privat chat
else:
# send a different message
I know how to handle a response to a command sent by the user in the telegram chat, but not how to send a message to a user without receiving a command first. I think there fore I would need to have a way to store the users chat Id first to later refer to that Id when sending the message.
The point is I want to compile my program to .exe later on and send it to some friends and it should work for them as well.
It is very easy, just use a simple database.
MongoDB is the best choose in my opinion.
Create an account on it and follow this tutorial.
First get the user_id
userid1 = str(update.message.chat_id)
Then store it into the database
import pymongo
from pymongo import MongoClient
cluster = MongoClient("mongodb+srv://<user>:<password>#cluster0.uubct.mongodb.net/users?retryWrites=true&w=majority")
db = cluster["users"]
collection = db["users"]
results = collection.find({"_id": int(userid1)})
if results.count() == 0:
print("post")
post = {"_id": int(userid1)}
collection.insert_one(post)
else:
print("User already in the database!")
For getting it you need to use the find() method.
results = collection.find()
for result in results:
var1 = (result["_id"])
print(var1)
context.bot.send_message(chat_id=prova,
text = "Hi")
You can simply add the id in a list WHITOUT ANY THIRD PARTS PAKAGE
import telebot
TOKEN = ""
bot = telebot.TeleBot(TOKEN)
admin = # your chat id
users = []
#bot.message_handler(commands=['start'])
def start_message(msg):
bot.send_message(msg.chat.id, 'Welcome!')
if msg.chat.id not in users: # if the id isn't already in the users list
users.append(msg.chat.id)
#bot.message_handler(commands=['send_at_all']) # A way to use the list
def sendAtAll(msg):
if msg.chat.id == admin: # only if YOU start the command the message will be sent
for id in users: # for every user that has start the bot
bot.send_message(id, "I'm sending this message at all the users")
# If an user wants to stop the notifications...
#bot.message_handler(commands=['unsubscribe'])
def sendAtAll(msg):
del users[msg.chat.id]
bot.send_message(msg.chat.id, "If you want to receive the notification click /start")
# Every time you are going to restart the bot polling the content of the users list will be deleated so...
#bot.message_handler(commands=['save_user_list'])
def sendAtAll(msg):
if msg.chat.id == admin:
bot.send_message(admin, users)
# the list will be sent to your telegram chat, when you activate the bot you can add the list manually
bot.polling()
You can also create a class and save every chat id as an object
import telebot
from random import choice
TOKEN = ''
bot = telebot.TeleBot(TOKEN)
admin = # your chat id
users = []
class Userbot: # The class User is already in the pyTelegramBotAPI
def __init__(self, msg):
self.id = msg.chat.id
self.username = '#' + msg.from_user.username
def contestWinner(self):
text = f'Hi {self.username}, you have win!!!'
bot.send_message(self.id, text)
#bot.message_handler(commands=['start'])
def start(msg):
bot.send_message(msg.chat.id, 'Welcome!')
for el in users:
if msg.chat.id not in el.id:
users.append(Userbot(msg))
# you can't type 'if msg.chat.id not in users.id' because only the object inside the list can use the method id
#bot.message_handler(commands=['extract']) # another way to use the list
def extract(msg):
if msg.chat.id == admin:
winner = choice(users)
winner.contestWinner()
#bot.message_handler(commands=['unsubscribe'])
def sendAtAll(msg):
for el in users:
if msg.chat.id == el.id:
del users[el]
# only if the user inside the object is the same as the user that has sent the message the object will be deleated
bot.send_message(msg.chat.id, "If you want to receive the notification click /start")
#bot.message_handler(commands=['save_user_list'])
def sendAtAll(msg):
if msg.chat.id == admin:
bot.send_message(admin, users)
bot.polling()
Apologise for my terrible english

How to handle received contacts with pyTelegramBotAPI?

I want to create something like feedback form in my telegram bot.
User fills in some information & at the end - sends his phone number (as contact). The Bot ought to copy the contact, append some information & forwad/send formed message to an admin.
I'm using this markup:
contact_btn = types.ReplyKeyboardMarkup(resize_keyboard=True)
send_contact = types.KeyboardButton("Confirm", request_contact=True)
cancel = types.KeyboardButton("Cancel")
send_contact_btn.add(send_contact, cancel)
bot.send_message(message.chat.id, "Confirm the operation:", reply_markup=contact_btn)
I would like to check if this contact belongs to the sender or not & forward/send received contact by using:
bot.forward_message(???)
bot.send_message(???)
How can i do it?
someone on the internet suggests to check if user_id in from object is equal to user_id in Contact. Origin

Telethon - Error when retrieve user info

I'm stuck with an error in telethon, when trying to get users data.
First, I get new messages from some groups, it's ok, but when I try to get user data (name, first_name etc) - sometimes it's ok, but mostly fails with error
ValueError: Could not find the input entity for "12345678".
Please read https://telethon.readthedocs.io/en/latest/extra/basic/entities.html
to find out more details.
I read that article a lot of times, tried to use also client.get_input_entity as it says, but it doesn't help
Here is my code:
import logging
from telethon import TelegramClient, events
logging.basicConfig(level=logging.WARNING)
logging.getLogger('asyncio').setLevel(logging.ERROR)
entity = 'session' # session
api_id = 123456
api_hash = 'hash'
phone = '1234567'
chats = ['group1', 'group2', 'group3']
client = TelegramClient(entity, api_id, api_hash)
#client.on(events.NewMessage(chats=chats))
async def normal_handler(event):
print(event.message.message)
print(event.date)
print(event.from_id)
print(event.message.to_id)
#user = await client.get_input_entity(event.from_id)
user = await client.get_entity(event.from_id)
client.start()
client.run_until_disconnected()
How can I fix that?
And one more question, how can I retrieve info about group?
I know it's id from event.message.to_id, but can't get how to get it's name.
The docs for the library looks not very friendly for beginners. =(
Thank you
Telegram does not allow to get user profile by integer id if current client had never "saw" it.
Telethon documentation (https://telethon.readthedocs.io/en/latest/extra/basic/entities.html) suggests following options to make contact "seen":
if you have open conversation: use client.get_dialogs()
if you are in same group: use client.get_participants('groupname')
if you are it was forward in group: use client.get_messages('groupname', 100)
Choose which one is applicable in your case. One of them will make contact "seen", and it will be possible to use client.get_entity(event.from_id)

Django Channels

I've little question about Django Channels, WebSockets, and chat applications. Serving with google gets me to chatrooms, where people can connect and start a chat. But I don't know how one user can send another user instant message.
For example:
1) I add John to friends, and want to start chat.
2) On server side I can generate object Room, with me and John as members.
3) When I send message via WebSocket to this room, I know for who this message is, but I don't know how to get John's channel
#channel_session_user_from_http
def ws_connect(message):
rooms_with_user = Room.objects.filter(members=message.user)
for r in rooms_with_user:
Group('%s' % r.name).add(message.reply_channel)
#channel_session_user
def ws_receive(message):
prefix, label = message['path'].strip('/').split('/')
try:
room = Room.objects.get(name=label)
except Exception, e:
room = Room.objects.create(name=get_random_string(30))
for u in message.chmembers:
room.members.add(u)
# here can be somethis like this
# try
reply_channel = Channels.objects.get(online=True, user=u)
Group('%s' % r.name).add(reply_channel)
Group('%s' % room.name).send({
"text": "%s : %s" % (message.user.username, message['text']),
})
#channel_session_user
def ws_disconnect(message):
prefix, label = message['path'].strip('/').split('/')
Group(label).discard(message.reply_channel)
Simply make "automatic unique rooms" for user pairs. The rest stays the same. For example like this
def get_group_name(user1, user2):
return 'chat-{}-{}'.format(*sorted([user1.id, user2.id]))
Give it two user objects, and it returns a unique room for that pair of users, ordered the User.id, something like "chat-1-2" for the users with User.id "1" and "2".
That way, a user can connect with more than one logged-in device and still get the messages sent between the two users.
You can get the authenticated user's object from message.user.
For the receiving User object, I'd just sent the username along with the message. Then you can unpack it from the message['text'] the same way you unpack the actual message.
payload = json.loads(message.content['text'])
msg = payload['msg']
sender = message.user
receiver = get_object_or_404(User, username=payload['receiver'])
# ... here you could check if they have required permission ...
group_name = get_group_name(sender, receiver)
response = {'msg': msg}
Group(group_name).send({'text': json.dumps(response)})
# ... here you could persist the message in a database ...
So with that, you can drop all the "room" things from your example, including the room table etc. Because group names are always created on-the-fly when a message is send between two users.
Another important thing: One user will connect later than the other user, and may miss initial messages. So when you connect, you probably want to check some "chat_messages" database table, fetch the last 10 or 20 messages between the user pair, and send those back. So users can catch up on their past conversation.

Categories

Resources