簡體   English   中英

通過 python 向 Telegram Bot 發送短信

[英]Send text message via python to the Telegram Bot

我從早上開始就一直在嘗試,但早些時候出現了錯誤,所以我有了方向,但現在沒有錯誤,甚至沒有警告..

代碼的樣子:

import requests

def send_msg(text):
token = "TOKEN"
chat_id = "CHATID"
url_req = "https://api.telegram.org/bot" + token + "/sendMessage" + "?chat_id=" + chat_id + "&text=" + text 
results = requests.get(url_req)
print(results.json())

send_msg("hi there 1234")

什么是預期 output:它應該發送一條短信

當前的 output 是什么:它什么也不打印

有人幫忙的話會很有幫助,謝謝大家

編輯:2

由於未安裝以下依賴項,因此無法發送文本。

$ pip install flask
$ pip install python-telegram-bot
$ pip install requests

現在有人可以幫我發送照片嗎? 我認為它無法通過 URL 發送圖像,謝謝大家

**編輯 3 **

我從這里找到了圖像或視頻共享 url 但我的圖像是本地圖像而不是來自遠程服務器

您的代碼沒有任何問題。 您需要做的就是適當的縮進。

發生此錯誤主要是因為您的代碼中存在空格或制表符錯誤。 由於 Python 使用過程語言,如果您沒有正確放置制表符/空格,您可能會遇到此錯誤。

運行以下代碼。 它會正常工作:

導入請求

def send_msg(text):
   token = "your_token"
   chat_id = "your_chatId"
   url_req = "https://api.telegram.org/bot" + token + "/sendMessage" + "?chat_id=" + chat_id + "&text=" + text 
   results = requests.get(url_req)
   print(results.json())

send_msg(""Hello there!"")

發送圖片bot.sendPhoto(chat_id, 'URL')

注意:最好將編輯器配置為使制表符和空格可見以避免此類錯誤。

為我工作

在電報 my_token = '' 上與@BotFather 交談可以生成的導入電報#token

def send(msg, chat_id, token=my_token): """ 向 chatId 上指定的電報用戶發送消息 chat_id 必須是數字。""" bot = telegram.Bot(token=token) bot,sendMessage(chat_id=聊天ID,文本=味精)

這是一個使用流行的requests庫正確編碼 URL 參數的示例。 如果您只想發送純文本或 Markdown 格式的警報消息,這是一種簡單的方法。

import requests


def send_message(text):
    token = config.TELEGRAM_API_KEY
    chat_id = config.TELEGRAM_CHAT_ID

    url = f"https://api.telegram.org/bot{token}/sendMessage"
    params = {
       "chat_id": chat_id,
       "text": text,
    }
    resp = requests.get(url, params=params)

    # Throw an exception if Telegram API fails
    resp.raise_for_status()

有關如何為群聊設置 Telegram 機器人的完整示例和更多信息,請參閱此處的自述文件

下面也同樣使用 asyncio 和aiohttp客戶端,通過捕獲 HTTP 代碼 429 來限制消息。如果您沒有正確限制,Telegram 將踢出機器人。

import asyncio
import logging

import aiohttp

from order_book_recorder import config


logger = logging.getLogger(__name__)


def is_enabled() -> bool:
    return config.TELEGRAM_CHAT_ID and config.TELEGRAM_API_KEY


async def send_message(text, throttle_delay=3.0):
    token = config.TELEGRAM_API_KEY
    chat_id = config.TELEGRAM_CHAT_ID

    url = f"https://api.telegram.org/bot{token}/sendMessage"
    params = {
       "chat_id": chat_id,
       "text": text,
    }

    attempts = 10

    while attempts >= 0:
        async with aiohttp.ClientSession() as session:
            async with session.get(url, params=params) as resp:
                if resp.status == 200:
                    return
                elif resp.status == 429:
                    logger.warning("Throttling Telegram, attempts %d", attempts)
                    attempts -= 1
                    await asyncio.sleep(throttle_delay)
                    continue
                else:
                    logger.error("Got Telegram response: %s", resp)
                    raise RuntimeError(f"Bad HTTP response: {resp}")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM