Sending Messages with Telegram - APIs or Cli

Sending messages with Telegram - APIs or CLI?

First create a bash script for telegram called tg.sh:

#!/bin/bash
now=$(date)
to=$1
subject=$2
body=$3
tgpath=/home/youruser/tg
LOGFILE="/home/youruser/tg.log"
cd ${tgpath}
${tgpath}/telegram -k ${tgpath}/tg-server.pub -W <<EOF
msg $to $subject
safe_quit
EOF
echo "$now Recipient=$to Message=$subject" >> ${LOGFILE}
echo "Finished" >> ${LOGFILE}

Then put the script in the same folder than your python script, and give it +x permission with chmod +x tg.sh

And finally from python, you can do:

import subprocess
subprocess.call(["./tg.sh", "user#****", "message here"])

How do I send & receives Telegram messages programmatically?

Have a look at MTProto libraries like telethon or pyrogram. They are user-friendly (with lots of helper functions to abstract raw telegram api calls and their interfaces somewhat resemble the telegram bot api)

Here is a sample code (from the telethon docs):

from telethon import TelegramClient

# Remember to use your own values from my.telegram.org!
api_id = 12345
api_hash = '0123456789abcdef0123456789abcdef'

client = TelegramClient('anon', api_id, api_hash)

async def main():
# You can send messages to yourself...
await client.send_message('me', 'Hello, myself!')
# ...to some chat ID
await client.send_message(-100123456, 'Hello, group!')
# ...to your contacts
await client.send_message('+34600123123', 'Hello, friend!')
# ...or even to any username
await client.send_message('TelethonChat', 'Hello, Telethon!')

with client:
client.loop.run_until_complete(main())

How can I send a message to someone with my telegram bot using their Username

You can't send message to users using their username that is in form of @username, you can just send messages to channel usernames which your bot is administrator of it. Telegram bot api uses chat_id identifier for sending messages. If you want to achieve chat_id of users, you can use telegram-cli, but it's not easy at all because that project is discontinued and you should debug it yourself.
in your case you should do following command:

> resolve_username vahid_mas

and the output will be something like this:

{
"user": {
"username": "Vahid_Mas",
"id": "$010000006459670b02c0c7fd66d44708",
"last_name": "",
"peer_type": "user",
"print_name": "Vahid",
"flags": 720897,
"peer_id": 191322468,
"first_name": "Vahid",
"phone": "xxxxxxx"
},
"online": false,
"event": "online-status",
"state": -1,
"when": "2017-01-22 17:43:16"
}


Related Topics



Leave a reply



Submit