首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >通过python将短信发送到电报Bot

通过python将短信发送到电报Bot
EN

Stack Overflow用户
提问于 2020-07-26 16:52:31
回答 3查看 10.6K关注 0票数 3

我从早上起就一直在尝试,但早些时候有错误,所以我有了方向,但现在没有错误,甚至没有警告。

代码的外观:

代码语言:javascript
运行
复制
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")

预期的输出:它应该发送一条文本消息。

当前的输出是什么:它什么也不打印。

如果有人帮忙会很有帮助的,谢谢大家

编辑: 2

由于没有安装下列受抚养人,因此无法发送文本。

代码语言:javascript
运行
复制
$ pip install flask
$ pip install python-telegram-bot
$ pip install requests

现在谁能帮我拿一下sendPhoto吗?我认为它不能通过URL发送图像,谢谢大家

**编辑3**

我从这里中找到了一个图片或视频共享url,但是我的映像是本地的,而不是来自远程服务器的。

EN

回答 3

Stack Overflow用户

发布于 2020-07-26 17:23:12

您的代码没有任何问题。您所需要做的就是正确的缩进。

发生此错误的主要原因是代码中存在空格或制表符错误。由于Python使用过程语言,如果没有正确放置制表符/空格,则可能会遇到此错误。

运行以下代码。它会工作得很好:

代码语言:javascript
运行
复制
import requests

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库:bot.sendPhoto(chat_id, 'URL')发送图片可能更容易

注意:将编辑器配置为使制表符和空格可见以避免此类错误是一个好主意。

票数 5
EN

Stack Overflow用户

发布于 2020-07-26 16:56:27

这对我来说很管用:

代码语言:javascript
运行
复制
import telegram
#token that can be generated talking with @BotFather on telegram
my_token = ''

def send(msg, chat_id, token=my_token):
    """
    Send a mensage to a telegram user specified on chatId
    chat_id must be a number!
    """
    bot = telegram.Bot(token=token)
    bot.sendMessage(chat_id=chat_id, text=msg)
票数 0
EN

Stack Overflow用户

发布于 2021-10-13 13:25:49

下面是一个使用流行的requests库正确编码URL参数的示例。如果您只想发送纯文本或标记格式的警报消息,这是一个简单的方法。

代码语言:javascript
运行
复制
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 bot的完整示例和更多信息,请参见此处的自述

下面使用异步和aiohttp客户机也是一样的,通过捕获HTTP代码429来控制消息。如果你没有正确的油门,电报会把机器人踢出去。

代码语言:javascript
运行
复制
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}")
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63103077

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档