How can I send a message to #BotFather programmatically? - bots

I know that a bot can be created in a telegram if you send the command /newbot to the bot #BotFather. But to do this, you need to take your device, open Telegram, open a chat with #BotFather and send him the command /newbot. Can all of the above be done programmatically?
P.S.: this is not laziness, but an attempt to optimize the solution.

Yes, it's possible to create such interaction with mtproto libraries (pyrogram, telethon, madelineproto, etc...)
Here is a PoC script using telethon (python3 -m pip install -U telethon first to install the dependency):
from telethon import TelegramClient, events
api_id = ...
api_hash = "..."
client = TelegramClient('session', api_id, api_hash)
BOT_NAME="..."
BOT_USER_NAME="..." # must end with -bot
#client.on(events.NewMessage)
async def message_handler(event):
if 'Please choose a name for your bot' in event.raw_text:
await event.reply(BOT_NAME)
elif 'choose a username for your bot' in event.raw_text:
await event.reply(BOT_USER_NAME)
elif 'Done! Congratulations on your new bot' in event.raw_text:
print("Bot created!")
await client.disconnect()
async def main():
await client.send_message('botfather', '/newbot')
with client:
client.loop.run_until_complete(main())
client.run_until_disconnected()
You acquire the app_id and app_hash values from https://my.telegram.org/
and here is telethon's doc.

Related

How do i make a discord bot receive text after a command

I want to become a fake discord bot, so i can use: !!send or something like that.
I have the token ready and i tried some repl.it templates but i have no idea of what to do.
here is the code i tried:
import discord
import os
import time
import discord.ext
from discord.utils import get
from discord.ext import commands, tasks
from discord.ext.commands import has_permissions, CheckFailure, check
os.environ["TOKEN"] = "no-token-for-you-to-see-here"
#^ basic imports for other features of discord.py and python ^
client = discord.Client()
client = commands.Bot(command_prefix = '!!') #put your own prefix here
#client.event
async def on_ready():
print("bot online") #will print "bot online" in the console when the bot is online
#client.command(pass_context=True)
async def send(ctx,*,message):
await client.say(message)
client.run(os.getenv("TOKEN")) #get your bot token and create a key named `TOKEN` to the secrets panel then paste your bot token as the value.
#to keep your bot from shutting down use https://uptimerobot.com then create a https:// monitor and put the link to the website that appewars when you run this repl in the monitor and it will keep your bot alive by pinging the flask server
#enjoy!
It was online, but the command didn't work.
The command send should be
#client.command()
async def send(ctx, *, message: str):
await ctx.send(message)
Also, you're defining two client(s). You need only one.
client = commands.Bot(command_prefix = '!!')
You're also importing some useless modules that you don't need right now.
Your final code should look like this:
import discord
from discord.ext import commands
client = commands.Bot(command_prefix="!!")
#client.event
async def on_ready():
print("The bot is online")
#client.command()
async def send(ctx, *, message: str):
await ctx.send(message)
client.run("token-of-the-bot")
Please tell me if it works or not. Have a great day :)

Secret chat session in python telethon

How can i start a secret chat session using telethon? I've found a solution on the web; https://pypi.org/project/telethon-secret-chat/, but i'm not sure how it is supposed to work. I understand all the other stuff but what is supposed to go inside in the manager.start_secret_chat(target) function?
from telethon import TelegramClient
from telethon_secret_chat import SecretChatManager
client = TelegramClient('log', app_id, app_hash)
async def replier(event):
# all events are encrypted by default
if event.decrypted_event.message and event.decrypted_event.message == "hello":
await event.reply("**hi**") # parse_mode is markdown by default
async def new_chat(chat, created_by_me):
if created_by_me:
print("User {} has accepted our secret chat request".format(chat))
else:
print("We have accepted the secret chat request of {}".format(chat))
manager = SecretChatManager(client, auto_accept=True,
new_chat_created=new_chat) # automatically accept new secret chats
manager.add_secret_event_handler(func=replier) # we can specify the type of the event
with client:
client.run_until_disconnected()
manager.start_secret_chat(target)
Target can be the user_id. See this example:
# wait for incoming message
#client.on(events.NewMessage)
async def incoming_message_handler(event):
userId = event.original_update.user_id
# start secret chat
await manager.start_secret_chat(userId)

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

Simple bot command is not working in discord.py

I want to know in which text channels admin want to enable my bot functions. But in this case my code is not working.
The main idea was when admin typing !enable in text-chat, bot reacts to it and add text-chat id, guild id(ctx.channel.id) to the list, then bot responds in chat with bot has been enabled.
code where this command is not working:
channel = []
#bot.command()
async def enable(ctx):
global channel
print("Debug")
await ctx.send('Restriction bot has been enabled for this text channel.')
channel.append(ctx.channel.id)
full bot code:
import discord
from discord.ext import commands
bot = commands.Bot(command_prefix='!')
#bot.event
async def on_ready():
print(f'We have logged in as {bot.user.name}.')
channel = []
#bot.command()
async def enable(ctx):
global channel
print("Debug")
await ctx.send('Restriction bot has been enabled for this text channel.')
channel.append(ctx.channel.id)
#bot.event
async def on_message(ctx):
if ctx.author == bot.user:
return
#if ctx.channel.id != [for channnels in channel]:
# return
if ctx.attachments[0].height:
await ctx.author.send('Your media file is restricted!')
await ctx.delete()
The channel variable is initialized in your program so each time you will restart your bot, it will be emptied. One way you can solve your problem is by storing them in a file. The easiest way to do it would be to use the json library. You'll need to create a channels.json file.
The code :
from json import loads, dumps
def get_data():
with open('channels.json', 'r') as file:
return loads(file.read())
def set_data(chan):
with open('channels.json', 'w') as file:
file.write(dumps(chan, indent=2))
#bot.command()
async def enable(ctx):
channels = get_data()
channels.append(ctx.channel.id)
set_data(channels)
await ctx.send('Restriction bot has been enabled for this text channel.')
The channels.json file :
[]

Keeeping the loop going until input (discord.py)

I'm running a discord.py bot and I want to be able to send messages through the IDLE console. How can I do this without stopping the bot's other actions? I've checked out asyncio and found no way through.
I'm looking for something like this:
async def some_command():
#actions
if input is given to the console:
#another action
I've already tried pygame with no results but I can also try any other suggestions with pygame.
You can use aioconsole. You can then create a background task that asynchronously waits for input from console.
Example for async version:
from discord.ext import commands
import aioconsole
client = commands.Bot(command_prefix='!')
#client.command()
async def ping():
await client.say('Pong')
async def background_task():
await client.wait_until_ready()
channel = client.get_channel('123456') # channel ID to send goes here
while not client.is_closed:
console_input = await aioconsole.ainput("Input to send to channel: ")
await client.send_message(channel, console_input)
client.loop.create_task(background_task())
client.run('token')
Example for rewrite version:
from discord.ext import commands
import aioconsole
client = commands.Bot(command_prefix='!')
#client.command()
async def ping(ctx):
await ctx.send('Pong')
async def background_task():
await client.wait_until_ready()
channel = client.get_channel(123456) # channel ID to send goes here
while not client.is_closed():
console_input = await aioconsole.ainput("Input to send to channel: ")
await channel.send(console_input)
client.loop.create_task(background_task())
client.run('token')

Resources