Marx Babu
Marx Babu

Reputation: 760

How to send python output to telegram CHANNEL not to Group and gmail email group

Hi I have a program in python that generates results every one hour. The result can be of anything.This program will run in local machine or in the virtual private network.

I have two requirements 1. Send this python generated result to one telegram group [Group name "ourworld"](created by me) automatically without user intervention . (I have desktop telegram client running or web.telegram.org running in the same system)

  1. Send this result to gmail group email ID.

what are the methods available to achieve this requirement .Is there any working code available to do this job .Please share the info and details.

Edit:

The Issue that i am facing :

1.created a Bot using BotFather. 2.Adding this Bot to my Group ,Here i get an error could not add an member So added the Bot as admin in the group 3.Token of the BOT noted down. 4. Trying to get ChatId in this forum (https://web.telegram.org/#/im?p=g154513121) someone says number after p=g is the chartid ,In my case there is no number it shows @testingname like this.

  1. Using this approach trying to get the Chat ID https://api.telegram.org/bot738909732:AAE-2l7xAAlYHBXprK_a_bex09g9DMZbbDI/getme so here 738909732 become a chat Id (in this case why we need seperate call for the chart id) here it is true as response coming! Here the chat id is the ID of the my "testingname" no chart id generated for the group. 6.Now packing the URL to see the response i am getting this error.

https://api.telegram.org/bot738909732:AAE-2l7xAAlYHBXprK_a_bex09g9DMZbbDI/sendMessage?chat_id=738909732&text=testing

the output if i run this in browser

{"ok":false,"error_code":400,"description":"Bad Request: chat not found"} {"ok":false,"error_code":403,"description":"Forbidden: bot can't send messages to bots"}

How to resolve this issue and make the BOT working .why i am not able to add BOT to my group that says error "Cant Add user"

How to make this telegram group working.

Note : Using BotFather BOT created

Upvotes: 5

Views: 14133

Answers (5)

M_H
M_H

Reputation: 21

For sending a message to a Telegram chat you need a bot token and a public group

And for sending a message to an email you need a Gmail with SMTP password (how to get password?)

You can use this code, just change variables with your own parameter.

import requests

import urllib.parse

from smtplib import SMTP
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText



token = "<BOT_TOKEN>"
sender_email = "[email protected]"
sender_email_password = "<SMTP_PASS>"
receiver_email = "[email protected]"



email_html = """
<!DOCTYPE html>
<html lang="fa" xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="x-apple-disable-message-reformatting">
    <title>Sending Data</title>
</head>

<body>
    <main>
        <header><h1>Here is the data</h1></header>
        <hr>
        <p>
            {data}
        </p>
    </main>
    </body>
</html>"""


def send_data(data):
    # Send to email
    msg = MIMEMultipart('alternative')
    msg.attach(MIMEText(email_html.format(data=data), 'html'))
    msg['Subject'] = "Data"
    msg['From'] = sender_email
    msg['To'] = receiver_email
    server = SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login(sender_email, sender_email_password)
    server.sendmail(sender_email, receiver_email, msg.as_string())
    server.quit()
    # send to telegram chat
    requests.get(f"https://api.telegram.org/{token}/sendMessage?chat_id=@<CHAT_USERNAME>&text={urllib.parse.quote(data, safe='')}")



send_data("<DATA>")

Upvotes: 0

bipin_s
bipin_s

Reputation: 465

to send message to the telegram "group" without any user intervention , you require a telegram bot. create one using telegram bot-father. take a look at this link. also note the token while creating the bot. This method will work only for telegram Group .Telegram channel another method to be followed which MarxBabu answered below in his answers post.

import requests

# telegram url
url = "https://api.telegram.org/bot<Token>"

def send_mess(text):
    params = {'chat_id':-xxxxxxx, 'text': text}
    response = requests.post(url + 'sendMessage', data=params)
    return response


send_mess(result_you_want_to_send) 

to get the chat_id follow the steps mentioned here. note: group chat id's always starts with '-' . e.g. of group chat_id -356163873. A token and chat_id is only what you require to send message to telegram group.

for sending group emails you have to search more as i do not know much

Upvotes: 6

Marx Babu
Marx Babu

Reputation: 760

In case for sending message to telegram group the above method provided by bipin_s works where the chat_id = -xxxxxx is used.This is correct id followed by - symbol to be used.

For Posting message in the "telegram channel " a minor change needs to be done in the URL.The URL must be framed as below .

url = "https://api.telegram.org/botTokenID/sendMessage?chat_id=@yourChannelChatID&text=message"

Replace the TokenID with your BOT tokenID replace the yourChannelChatID with your channel chart id.Please note that the channel id is not negative id.

the code will look like this

import request

url = "https://api.telegram.org/botXyz:wwwwDFSJSJSAX/sendMessage?chat_id=@telechanneltesting&text=message"
requests.post(url)

Here the "message" as in the URL it will be posted in telegram channel.

How to get channel id ? Go to https://web.telegram.org/#/im in browser ,after login now search your "channel".Now in the browser address bar you will one link like https://web.telegram.org/#/im?p=@llliopppppsssssr

p=@llliopppppsssssr after the equal symbol what comes is channel chat ID.

Upvotes: 6

Osama Anees
Osama Anees

Reputation: 47

You can send emails in python through SMTP or using the Mailgun Api

I personally prefer using Mailgun as it is easier to setup and sending an email is as easy as sending a post request to mailgun. You can get the free version of the api and add your group email id to the sandbox (to avoid spam) and then use requests to post an email with the given api token

Upvotes: 0

lfkopp
lfkopp

Reputation: 104

I have it running on a Raspberry pi. You must look for botfather to get your telegram token.

import telepot 
from telepot.loop import MessageLoop
telegram_token = 'xxxx:xxxxxx'
user = 4444444
bot = telepot.Bot(telegram_token)
bot.sendMessage(user, 'Hey!')

For configuring gmail I don't have something here right now...

Upvotes: 0

Related Questions