How to change Telegram channel name? - python-3.x

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.

Related

Trouble with limit access to a Telegram Bot

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)

How to disconnect telegram client?

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()

Is it possible to create a telethon client starting from auth_key only?

The hello world of telethon looks like:
from telethon import TelegramClient
client = TelegramClient(name, api_id, api_hash)
async def main():
# Now you can use all client methods listed below, like for example...
await client.send_message('me', 'Hello to myself!')
with client:
client.loop.run_until_complete(main())
Like this it will ask me to sign in the first time, by providing phone and confirmation code.
Next time it will reuse information stored locally.
What i want is to give it a auth_key and use that.
So basically i want it to look like this:
from telethon import TelegramClient
auth_key = "ca03d.....f8ed" # a long hex string
client = TelegramClient(name, api_id, api_hash, auth_key=auth_key)
async def main():
# Now you can use all client methods listed below, like for example...
await client.send_message('me', 'Hello to myself!')
with client:
client.loop.run_until_complete(main())
While it is possible to use the auth_key directly, there are better options available, such as using StringSession as documented:
from telethon.sync import TelegramClient
from telethon.sessions import StringSession
# Generating a new one
with TelegramClient(StringSession(), api_id, api_hash) as client:
print(client.session.save())
# Converting SQLite (or any) to StringSession
with TelegramClient(name, api_id, api_hash) as client:
print(StringSession.save(client.session))
# Usage
string = '1aaNk8EX-YRfwoRsebUkugFvht6DUPi_Q25UOCzOAqzc...'
with TelegramClient(StringSession(string), api_id, api_hash) as client:
client.loop.run_until_complete(client.send_message('me', 'Hi'))
Be careful not to share this string, as anyone would gain access to the account. This string contains the auth_key (as you wanted) along with other required information to perform a successful connection.

How to remove a user from my telegram contacts using telethon?

I want to remove a user from a client's contact list.
My aim is to remove a user, which was added to the contact list with a phone number, from a contact list of a client.
I have followed this and this to add a user to a client's contact list. But can't figure out how to remove that user from the contact list.
I have searched for the telethon doc, And I'm sure it's somewhere in there but found nothing related for hours.
The code to add a user to contact list is this.
client = TelegramClient(name, api_id, api_hash)
async def main():
contact = InputPhoneContact(client_id=random.randint(0,9999), phone = "+23xxxxxxxxxx", first_name="fname", last_name="lname")
result = await client(ImportContactsRequest(contacts=[contact]))
with client:
client.loop.run_until_complete(main())
To do so you need to use the raw API requests directly which can be found here. https://tl.telethon.dev/index.html
for your question, the request is DeleteContactsRequest which can be found at https://tl.telethon.dev/methods/contacts/delete_contacts.html and can be used as such.
from telethon.sync import TelegramClient
from telethon import functions, types
with TelegramClient(name, api_id, api_hash) as client:
result = client(functions.contacts.DeleteContactsRequest(
id=['username']
))
print(result.stringify())

How to make a bot DM a list of people? (Discord.py) (Rewrite)

So this sends a DM to whoever I #mention.
#bot.command(pass_context=True)
async def pm(ctx, user: discord.User):
await user.send('hello')
How could I change this to message a list of IDs in let's say a text file, or a list variable containing user IDs?
In other words, how can I message multiple people with one command?
You can use Client.get_user_info to get the User class for a specified id value, if it exists.
Here is an example of how this can be done.
#bot.command()
async def pm(ctx):
user_id_list = [1, 2, 3] # Replace this with list of IDs
for user_id in user_id_list:
user = await bot.get_user_info(user_id)
await user.send('hello')
Also note that you do not need pass_context=True as context is always passed in the rewrite version of discord.py. See here: https://discordpy.readthedocs.io/en/rewrite/migrating.html#context-changes
If you want to message multiple people from the command, you can use the new Greedy converter to consume as many of a certain type of argument as possible. This is slightly different than the *args syntax because it allows for other arguments of different types to come after it:
from discord.ext.commands import Bot, Greedy
from discord import User
bot = Bot(command_prefix='!')
#bot.command()
async def pm(ctx, users: Greedy[User], *, message):
for user in users:
await user.send(message)
bot.run("token")
Useage:
!pm #person1 #person2 #person3 This is my message!

Resources