|
我可以借,有需要可以私信我 本帖最后由 耳阝鱼禾 于 2024-11-18 22:18 编辑
- from telegram import Update
- from telegram.ext import Updater, MessageHandler, Filters, CallbackContext
- import logging
- import pickle
- import os
- from datetime import datetime, timedelta
- import pytz
- logging.basicConfig(level=logging.INFO)
- BOT_TOKEN = 'BOT KEY' #你的电报机器人KEY
- CHANNEL_ID = '频道ID' #你要监听的频道ID
- GROUP_ID = '群组ID' #将频道内容转发到这个群组的 群组ID
- PROCESSED_MESSAGES_FILE = 'processed_messages.pkl'
- def load_processed_messages():
- if os.path.exists(PROCESSED_MESSAGES_FILE):
- with open(PROCESSED_MESSAGES_FILE, 'rb') as f:
- return pickle.load(f)
- return set()
- def save_processed_message(message_id):
- processed_messages.add(message_id)
- with open(PROCESSED_MESSAGES_FILE, 'wb') as f:
- pickle.dump(processed_messages, f)
- os.chmod(PROCESSED_MESSAGES_FILE, 0o777)
- def reset_processed_messages():
- global processed_messages
- processed_messages = set()
- save_processed_message(None)
- def is_today_message(message_date):
- beijing_tz = pytz.timezone('Asia/Shanghai')
- now_beijing = datetime.now(beijing_tz)
- message_date_beijing = message_date.astimezone(beijing_tz)
- return message_date_beijing.date() == now_beijing.date()
- processed_messages = load_processed_messages()
- def forward_message(update: Update, context: CallbackContext):
- if update.channel_post and update.channel_post.chat.id == int(CHANNEL_ID):
- message_id = update.channel_post.message_id
- message_date = update.channel_post.date
- if is_today_message(message_date) and message_id not in processed_messages:
- context.bot.forward_message(chat_id=GROUP_ID, from_chat_id=CHANNEL_ID, message_id=message_id)
- save_processed_message(message_id)
- def main():
- updater = Updater(token=BOT_TOKEN, use_context=True)
- dispatcher = updater.dispatcher
- channel_handler = MessageHandler(Filters.chat(int(CHANNEL_ID)), forward_message)
- dispatcher.add_handler(channel_handler)
- updater.job_queue.run_daily(reset_processed_messages, time=datetime.time(0, 0, 0, tzinfo=pytz.timezone('Asia/Shanghai')))
- updater.start_polling()
- updater.idle()
- if __name__ == '__main__':
- main()
复制代码
# 安装方式用宝塔或者1panel的话
# 将代码在网站目录下创建 bot.py 文件
# 例如宝塔路径 /www/wwwroot/telegram/bot.py
# SSH 连接服务器
#安装python3环境
- sudo apt install python3-pip
复制代码
# CD到代码路径的目录
- cd /www/wwwroot/telegram/
复制代码
#在代码路径的目录下 安装依赖
- pip install python-telegram-bot pytz
复制代码- pip3 install -r requirements.txt
复制代码
查询环境
确保环境没问题后
开机自启,到宝塔 计划任务 创建任务 每小时执行一次
写入以下内容
- pkill -f bot.py
- cd /www/wwwroot/telegram
- nohup python3 bot.py &
复制代码
|
|