Telegram 机器人使用 Python 编码,问题是它无法将最后一个频道帖子的信息保存在数据库中,并且当频道不为空帖子时,它会打印消息“Channel post is None”Python 3.11。 5 我,python-telegram-bot 版本 20.6:
from typing import Final
from telegram import Update
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
import sqlite3
import telegram
TOKEN: Final = "66jbhkjdsakfasdfZR4zRyOmWUFXn8p1clR6iPVmD"
BOT_USERNAME = "@jbt_content_bot"
# Database connection
conn = sqlite3.connect('database.db')
c = conn.cursor()
# Create table if it doesn't exist
c.execute('''CREATE TABLE IF NOT EXISTS posts (
channel_id INTEGER PRIMARY KEY,
post_id INTEGER,
text TEXT,
photo TEXT,
mentions TEXT
)''')
# Command
async def start_command(update: Update , context : ContextTypes.DEFAULT_TYPE):
await update.message.reply_text("ok")
async def help_command(update: Update , context : ContextTypes.DEFAULT_TYPE):
await update.message.reply_text("im helper ")
async def getlastPostChannel_command (update: Update , context : ContextTypes.DEFAULT_TYPE):
if update.channel_post is not None:
# Get the channel ID from the update
channel_id = update.channel_post.chat.id
# Get the bot's ID
bot_id = context.bot.id
# Check if the bot is a member of the channel and has read access
try:
chat_member = context.bot.get_chat_member(channel_id, bot_id)
if chat_member.status not in ["creator", "administrator", "member", "restricted"]:
raise telegram.error.Unauthorized("The bot is not a member of the channel or has no read access.")
except telegram.error.Unauthorized as e:
# The bot was kicked from the channel or has no read access
print(f"Error: {e.message}")
return
# Get the last post of the channel
last_post = await context.bot.get_message(channel_id, -1)
# Save the post information to the database
c.execute('''INSERT INTO posts (channel_id, post_id, text, photo, mentions) VALUES (?, ?, ?, ?, ?)''',
(channel_id, last_post.message_id, last_post.text, last_post.photo.file_id,
last_post.caption_entities))
conn.commit()
# Send a confirmation message to the user
await update.message.reply_text('The last post of the channel has been saved to the database.')
else:
print("Channel post is None")
async def custom_command(update: Update , context : ContextTypes.DEFAULT_TYPE):
await update.message.reply_text("custome")
# Handel responses
def handel_response(text: str) -> str:
processed:str = text.lower()
if "hello" in processed:
return "hiiiiii"
elif "how are you" in processed:
return "i`m good"
elif "hello" in processed:
return "hiiiiii"
else:
return "sikitir"
async def handel_message(update: Update , context : ContextTypes.DEFAULT_TYPE):
if update.message is not None:
message_type: str = update.message.chat.type
text: str = update.message.text
print(f'User({update.message.id}) in {message_type}:{text}')
if message_type == 'group':
if BOT_USERNAME in text:
new_text: str = text.replace(BOT_USERNAME, '').strip()
response: str = handel_response(new_text)
else:
return
else:
response: str = handel_response(text)
print('Bot :', response)
await update.message.reply_text(response)
else:
print("Message is None")
async def error(update: Update, context: ContextTypes.DEFAULT_TYPE):
print(f'Update{update},caused error{context.error}')
if __name__ == '__main__':
print('Starting Bot')
app = Application.builder().token(TOKEN).build()
app.add_handler(CommandHandler('start', start_command))
app.add_handler(CommandHandler('help', help_command))
app.add_handler(CommandHandler('custom', custom_command))
app.add_handler(CommandHandler('post', getlastPostChannel_command))
# message
app.add_handler(MessageHandler(filters.TEXT, handel_message))
# Errors
app.add_error_handler(error)
# Polls
print('polling ...')
app.run_polling(poll_interval=2)
我正在使用 Telegram Bot API 21.4 和 Python 3.11.5 I,python-telegram-bot 版本 20.6,我试图将最后一个频道帖子的信息保存在数据库中,但我收到消息“频道帖子为无” .
我已检查以下内容:
机器人是频道成员并具有读取权限。 该频道不乏帖子。 我不知道为什么机器人无法将最后一个频道帖子的信息保存在数据库中。如果您能提供任何帮助,我将不胜感激。
在函数
getlastPostChannel_command
中,参数 update
是包含命令 /post
的消息。这不是您频道中的最后一篇帖子。
Telegram 在机器人进来时向其发送更新,PTB 处理程序设置旨在一一处理它们。请务必阅读PTBs教程。特别是,不存在Bot.get_message
这样的东西(另见这里) 因此您将需要一个处理频道帖子的处理程序。您已经有一个
MessageHandler(filters.TEXT, handel_message)
可以做到这一点。您只需要检查是否
update.channel_post is not None
。请注意,您也可以使用
filters.UpdateType.CHANNEL_POST
来实现此目的。
python-telegram-bot
的维护者。