How to remove a user from my telegram contacts using telethon? - python-3.x

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

Related

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

Discord.py welcome message for multiple servers

I am making a discord bot that I plan on being in multiple servers. Each server will have a different welcome channel name and all that. I made the welcome message and I tried making the bot post the message in a channel called "welcome" which would solve this problem but didn't work. I thought about making a database that saves the channel id that the server owner sends to the bot under the server name/ID. The bot when triggered would match the server ID to one in the database then grab the channel id linked to the server id. But that would be a lot of coding in SQL or PostgreSQL which I would have to learn how to get the bot to save the sever id and channel id to the database, How to get the bot to match the server id's then grab the channel id and posting it the message to the server. There is no documentation on discord py bots and making welcome messages for different servers. I was wondering if there is a better way to do it and how would I do it?
What I have so far in relation to the welcome message.
import discord
import logging
import asyncio
import random
import time
import tweepy, discord
from discord.ext import commands
from discord.ext.commands import bot
#File Imports
from config import *
client = commands.Bot(command_prefix='sec.')
# logger = logging.getLogger('discord')
# logger.setLevel(logging.DEBUG)
# handler = logging.FileHandler(filename='discord.log', encoding='utf-8', mode='w')
# handler.setFormatter(logging.Formatter('%(name)s: %(message)s'))
# logger.addHandler(handler)
#client.event
async def on_ready():
print('Logged in as %s' % client.user.name)
while True:
presence = random.choice(['sec.help', 'Defending Servers'])
activity = discord.Game(name=(presence))
await client.change_presence(status=discord.Status.online, activity=activity)
await asyncio.sleep(7)
client.remove_command('help')
#client.event
async def on_member_join(member):
# Adds role to user
# role = discord.utils.get(member.server.roles, name='Member')
# await client.add_roles(member, role)
# Random embed color
range = [255,0,0]
rand = random.shuffle(range)
# Welcomes User
embed = discord.Embed(title="{}'s info".format(member.name), description="Welcome too {}".format(member.guild.name))
embed.add_field(name="Name", value=member.name, inline=True)
embed.add_field(name="ID", value=member.id, inline=True)
embed.add_field(name="Status", value=member.status, inline=True)
embed.add_field(name="Roles", value=member.top_role)
embed.add_field(name="Joined", value=member.joined_at)
embed.add_field(name="Created", value=member.created_at)
embed.set_thumbnail(url=member.avatar_url)
inlul = client.get_channel(CHANNEL_ID)
await inlul.send(inlul, embed=embed)
If you find any documentation on this I would love to read it. All I could find are for bots that are basic and has you enter a channel id.
If the bot is on a much smaller scale, say just a few servers, then I'd say using a json file to save a dictionary wouldn't be a bad idea.
You can save the Id of the top text channel as a default when the server joins the server and let them change what channel to use with commands, this can be done with the on_guild_join event
import json
#sets value in json to guild id upon the bot joining the guild
#client.event
async def on_guild_join(guild):
#loads json file to dictionary
with open("filename.json", "r") as f:
guildInfo = json.load(f)
guildInfo[guild.id] = guild.text_channels[0] #sets key to guilds id and value to top textchannel
#writes dictionary to json file
with open("filename.json", "w") as f:
json.dump(guildInfo, f)
#allows server members to set channel for welcome messages to send to
#client.command()
async def welcomeMessage(ctx):
with open("filename.json", "r") as f:
guildInfo = json.load(f)
guildInfo[ctx.message.guild.id] = ctx.message.channel.id #sets channel to send message to as the channel the command was sent to
with open("filename.json", "w") as f:
json.dump(guildInfo, f)
then just use
with open("filename.json", "r"):
guildInfo = json.load(f)
channnel = guildInfo[ctx.message.guild.id]
to get the channel to send the message to and
channel.send(embed=embed)
to send the message
before running it ensure to have an empty json file in the same directory and add {} to the file.

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 change Telegram channel name?

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.

How to get server details of a member

How to get details of a member using his UserID. like example i want to know in which server(name and ID) he is member of were ever my bot is added.
It's as simple as looping through all of the servers the bot has access to and trying to retrieve the Member object from each server for that ID.
from discord.ext import commands
bot = commands.Bot(command_prefix='!')
#bot.command(pass_context=True)
async def getUser(ctx, id):
# id = int(id) # On the rewrite branch, ids are ints
for server in bot.servers:
member = server.get_member(id)
if member:
await bot.say(f"Server Name: {server.name}")
await bot.say(f"Server ID: {server.id}")
bot.run("TOKEN")

Resources