我正在修改一个旧机器人,使他从channel01向channel02发送任何电报消息。 这是可行的,但由于某种原因,它还转发了channel01的另一条消息(以及更旧的消息)。 我认为这与message_id有关,但不明白为什么会这样。
edit:我正在将此漫游器添加到两个通道中,所以我猜是channel02正在执行:
bot.forwardMessage(from_chat_id, to_chat_id, msg['message_id'])
那可以解释为什么它转发两条消息而不是一条消息,您怎么看? 我不知道如何解决这个问题。
反正这是我的代码:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json
import os
import sys
import telepot
import time
from telepot.loop import MessageLoop
def save_status(obj):
with open('chats.json', 'w') as f:
f.write(json.dumps(obj))
def save_allowed(s):
with open('allowed.json', 'w') as f:
f.write(json.dumps(list(s)))
if not os.path.isfile('chats.json'):
save_status({})
if not os.path.isfile('allowed.json'):
save_allowed(set())
chats = {}
allowed = []
TOKEN = ""
PASSWORD = "changeme"
with open('chats.json', 'r') as f:
chats = json.load(f)
with open('allowed.json', 'r') as f:
allowed = set(json.load(f))
if os.path.isfile('config.json'):
with open('config.json', 'r') as f:
config = json.load(f)
if config['token'] == "":
sys.exit("No token defined. Define it in a file called config.json.")
if config['password'] == "":
print("WARNING: Empty Password for registering to use the bot." +
" It could be dangerous, because anybody could use this bot" +
" and forward messages to the channels associated to it")
TOKEN = config['token']
PASSWORD = config['password']
else:
sys.exit("No config file found. Remember changing the name of config-sample.json to config.json")
def is_allowed(msg):
if msg['chat']['type'] == 'channel':
return True #all channel admins are allowed to use the bot (channels don't have sender info)
return 'from' in msg and msg['from']['id'] in allowed
def handle(msg):
print("Message: " + str(msg))
# Add person as allowed
content_type, chat_type, chat_id = telepot.glance(msg)
txt = ""
if 'text' in msg:
txt = txt + msg['text']
elif 'caption' in msg:
txt = txt + msg['caption']
if is_allowed(msg):
if txt != "":
bot.forwardMessage(from_chat_id, to_chat_id, msg['message_id'])
bot = telepot.Bot(TOKEN)
MessageLoop(bot, handle).run_as_thread()
print('Listening ...')
# Keep the program running.
while 1:
time.sleep(10)