Python send telegram message requests

How to send messages to telegram using Python

I have a python script in which logs messages to the console. But I also want those messages to be sent to the telegram using my bot. Any hint and suggestion will be helpful. Thanks in advance. I haven’t tried anything yet, just got thought if that possible or not and if it is then how?

Please see How do I ask a good question?. First you need to do research. StackOverflow is not a place for others to «write your code» — you should try things first, and once you have an error, search for it here. If you don’t find a solution, then it’s okay to ask a new question.

1 Answer 1

  1. Make A Telegram Bot Using BotFather for Telegram Search for BotFather in your Telegram client by opening it. A pre-installed Telegram bot that assists users in making original Telegram bots To create a new bot, enter /newbot. Name and username your bot. Copy the token for your new Telegram bot. Please take note that anyone who obtains your token has complete control over your Telegram bot, so avoid uploading it online.
  2. Obtaining a chat ID To send Telegram messages using Python, we require the conversation ID that each chat in Telegram holds.

Send a message to your Telegram bot (any random message) Use this Python program to locate your chat ID.

import requests TOKEN = "YOUR TELEGRAM BOT TOKEN" url = f"https://api.telegram.org/bot/getUpdates" print(requests.get(url).json()) 

The getUpdates function, which is invoked by this script, sort of checks for new messages. Our chat ID can be located in the JSON that was returned (the one in red)

Please take note that your results can be empty if you don’t message your Telegram bot. Copy the chat ID and paste it in the following step.

  1. Python-based Telegram message delivery The following Python script requires you to enter 1) your Telegram bot token and 2) your chat ID from the previous two steps. (Be sure to include modify your message.)
import requests TOKEN = "YOUR TELEGRAM BOT TOKEN" chat_id = "YOUR CHAT ID" message = "hello from your telegram bot" url = f"https://api.telegram.org/bot/sendMessage?chat_id=&text=" print(requests.get(url).json()) # this sends the message 

Run the Python script and check your Telegram!

Источник

How to send telegram messages with python tutorial

How to send telegram messages with python tutorial

Telegram provides an amazing Bot API for developer with the need of automation. The Telegram Bot API is HTTP-based and is useful in different scenearios. In this blog, we will guide you to configure the Bot to send messages with python.
For more information, you can go to the official site. Bot FAQ

Steps to configure Telegram Bot API with Python.

Читайте также:  Alt Attribute

  1. First you will need to open the BOTFATHER menu using this link: https://t.me/botfather
  2. The link will redirect you to your telegram.
  3. Now you will have a chat opened with the BotFather which you can start it right away by clicking start or writing «/start»
  4. To create a new Bot you will have to write in the chat «/newbot» and follow the steps to create a new bot.

5. To configure your bot please notice that you will be asked for this:

* Bot username (have to be unique and needs to end with the word «bot»)

The BotFather answer will contain the bot’s username (like any telegram user) and the HTTP API token which is used to control the bot. Please save the token in a secure place and don’t share it with anyone.

6. To activate your bot, please go to the link that has your bot’s username and in that chat click «start» or write «/start»

7. Add your bot to the group chat where you want the bot to send the messages to.

8.Once the bot is in a telegram group, you can use curl or your normal browser to get the ID of the chat that the bot is in with:

9. Get the group-id by filtering or looking into the results provided by the step 8 for the name of the telegram group and next to it, it will be the ID of the group (yes it can start with a «-«)

You can see something similar:

Let the bot write a message for you in the telegram group

With python you can use the requests library to send the message and get a response which can be used for error handling if is not 200.

$python3 >>> import requests >>> requests.get("https://api.telegram.org/bot/sendMessage?chat_id=&text=This is a test")

Sign up for more like this.

Windows containers how to. not?

Windows containers how to. not?

Things to know about Windows Containers This started as an initial research into Windows Containers. My initial impression was not fantastic, left wanting. * «Windows requires the host OS version to match the container OS version» (src) * This is in stark constrast compared to Linux containers, where you can trivially, swap

How to Create a Table of Contents on Ghost

How to Create a Table of Contents on Ghost

You know what’s scary? Ghosts. You know what’s even scarier? Not having a table of contents on your blog posts on Ghost! That’s why I’m going to show you how to make one in just a few easy steps. No coding required, no ghost hunting needed. Just follow me and you’ll be fine.

Читайте также:  Как на python создать gui

If I want to get a website set up and some SEO done, what sort of figures would I be looking at?

If I want to get a website set up and some SEO done, what sort of figures would I be looking at?

«for reals though, if it’s just a simple one page website, and to stick some keywords into google» . «Without more information I’d question why not use Squarespace, Wix, WordPress? They are all adequate. We also sell small business web hosting with support. . «Oh is it that easy?» . «Depends what «it»

Источник

Sending Telegram message from Python

So my question is: Should I go back to the older pytg? Can I fix the shell scripts or amend them to Python by inputting a stringIO from subprocess.call or popen? Is anyone out there using this in a robust fashion?

Background

  • http://www.instructables.com/id/Raspberry-remote-control-with-Telegram/ showing how to reply to a ‘ping’ message with a ‘pong’ message using a Lua script. Worked for me.
  • http://technofaq.org/posts/2014/06/chat-with-telegram-buddies-the-geeky-way-with-telegram-cli/

3 Answers 3

The first step is to create a bot and get the token .

The second step is go get the chat_id :

  • Write something in the chat
  • Visit https://api.telegram.org/bot/getUpdates and get the chat_id under the key message[‘chat’][‘id’] .

The last step is to use this code:

import requests def telegram_bot_sendtext(bot_message): bot_token = '' bot_chatID = '' send_text = 'https://api.telegram.org/bot' + bot_token + '/sendMessage?chat_id=' + bot_chatID + '&parse_mode=Markdown&text=' + bot_message response = requests.get(send_text) return response.json() test = telegram_bot_sendtext("Testing Telegram bot") print(test) 
  1. Talk to @BotFather . Send /newbot to them and follow the prompts. In response you will get an HTTP API token (it will look something like 123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11 ).
  2. Talk to your newly created bot, it is enough to just /start it.
  3. Immediately open https://api.telegram.org/bot/getUpdates?offset=-1 in your web-browser (literally paste the token you received from the BotFather, complete with all the letters and punctuation). Copy the chat id from the returned JSON object.
  4. With the data above, sending a message is a matter of a simple POST request. For example, using the Requests library:
import requests TOKEN = '. ' CHAT_ID = '. ' SEND_URL = f'https://api.telegram.org/bot/sendMessage' requests.post(SEND_URL, json=) 

I try this and it worked. My doubt: can I only send messages to the created bot? Can I do it to another chat? If so, how can I get the chat_id of it?

@MarioMey you do not send messages to the bot, you send messages from the bot to users who activated it. You can get chat_id s from your program by using that same getUpdates endpoint.

I’d rather use the package python-telegram-bot , it works well for me.

You can find here documentation and an easy example to get started.

In order to reply to text messages, you can add a MessageHandler after the CommandHandler such as:

updater.dispatcher.add_handler(MessageHandler(Filters.text, text_reply)) def text_reply(bot, updater): text = update.message.text if text == 'ping': reply = 'pong' elif text == 'pong': reply = 'ping' # add any process to the text else: reply = "I only respond to ping pong" update.message.reply_text(reply) 

Don’t forget to import from telegram.ext import MessageHandler .

Читайте также:  Объектно ориентированное программирование python программы

Источник

Как отправить сообщение в телеграм боте с помощью запроса?

Но вместе с этим нужно еще отправить параметр reply_markup, что бы вместе с сообщением поменялись кнопки. То есть нужно вставить ReplyKeyboardMarkup и 1 кнопку, допустим с названием «test». Как такое можно сделать?

P.S: нужно именно запросом, без telebot и тд

deepblack

curl -X POST \ -H 'Content-Type: application/json' \ -d '' \ https://api.telegram.org/bot$TELEGRAM_BOT_TOKEN/sendMessage
import requests import json proxy = token = '8888:ABC' chat_id = 88888 URL = 'https://api.telegram.org/bot' + token + '/sendMessage' reply_markup = < "keyboard": [["Yes", "No"], ["Maybe"], ["1", "2", "3"]], "resize_keyboard": True>data = r = requests.post(URL, data=data, proxies=proxy) print(r.json())

Прошу прощения за невежество. Я только пытаюсь разобраться с телеграмм ботами и их прграммированием. Есть необходимость отправлять в группу сообщения в формате JSON. У меня есть WEB HOOK сервер который по указанному HTTP адресу отправляет POST в JSON формате типа:

, "region": "ru-sve", "plate_index": 0, "processing_time_ms": 24.905000686645508, "candidates": [, , , , , , , , , ], "coordinates": [, , , ], "matches_template": 1, "plate_crop_jpeg": "/9j/4AAQSkZJRgA*******************.yrn+KigaP/9k=", "requested_topn": 10>, "vehicle": , , , , ], "color": [, , , , ], "make": [, , , , ], "body_type": [, , , , ], "year": [, , , , ], "make_model": [, , , , ]>, "best_uuid": "P7RKZU82SGESIFZHHPE87HXIWIVCS187I5DBLFZQ-2088894996-1624120829062", "epoch_end": 1624120837415, "best_image_width": 2304, "data_type": "alpr_group", "best_image_height": 1296, "frame_end": 5562318, "is_parked": false, "best_region": "ru-sve", "uuids": ["P7RKZU82SGESIFZHHPE87HXIWIVCS187I5DBLFZQ-**************-1624120823211", ""P7RKZU82SGESIFZHHPE87HXIWIVCS187I5DBLFZQ-**************-1624120837415"], "plate_indexes": [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], "travel_direction": 210.373291015625, "country": "ru", "best_plate_number": "A464BM19", "best_region_confidence": 97.6282730102539, "matches_template": true, "agent_version": "2.7.101", "candidates": [, , , , , , , , , 

Из него хочется отправить в группу несколько полей: best_plate_number (текст) и vehicle_crop_jpeg (картинка jpeg). Ну или все если это можно обработать в одной строке HTTP типа:

https://api.telegram.org/bot400000393:AAF2ZmXoDG***************ijNRs/sendMessage?chat_id=-1000000000099&text="json(best_plate_number)"

Вообще это возможно? Может пнете что почитать.

Источник

Оцените статью