我正在尝试用 Python 制作一个非常简单的 Telegram 机器人,它每分钟都会说“嗨”。这是到目前为止的代码,但它没有在我的电报中发布任何内容。
import requests
import time
bot_token = "insert_token_here"
group_chat_id = "insert_group_chat_id_here"
def send_message(chat_id, text):
url = f"https://api.telegram.org/bot{bot_token}/sendMessage"
payload = {
"chat_id": chat_id,
"text": text
}
requests.post(url, data=payload)
while True:
send_message(group_chat_id, "Hi")
time.sleep(60)
您可以尝试一下,但请确保您通过 pip/pip3 安装了“python-telegram-bot”。
import logging
from telegram import Bot
from telegram.ext import Updater, CommandHandler, CallbackContext
from datetime import datetime
import time
# Set your Telegram Bot Token here
TOKEN = "YOUR_TELEGRAM_BOT_TOKEN"
# Set your chat_id (replace with your chat_id)
CHAT_ID = "YOUR_CHAT_ID"
# Enable logging
logging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO)
logger = logging.getLogger(__name__)
# Define the function to send "Hi" message
def send_hi_message(context: CallbackContext):
context.bot.send_message(chat_id=CHAT_ID, text="Hi!")
def start(update, context):
update.message.reply_text('Bot is running!')
def main():
# Create the Updater and pass it your bot's token
updater = Updater(token=TOKEN)
# Get the dispatcher to register handlers
dp = updater.dispatcher
# Register the command handler
dp.add_handler(CommandHandler("start", start))
# Use the JobQueue to schedule the 'send_hi_message' function every minute
j = updater.job_queue
j.run_repeating(send_hi_message, interval=60, first=0)
# Start the Bot
updater.start_polling()
# Run the bot until you send a signal to stop (Ctrl+C)
updater.idle()
if __name__ == '__main__':
main()
将“YOUR_TELEGRAM_BOT_TOKEN”和“YOUR_CHAT_ID”替换为您的实际 Telegram 机器人令牌和聊天 ID。