本文整理汇总了Python中twx.botapi.TelegramBot.get_updates方法的典型用法代码示例。如果您正苦于以下问题:Python TelegramBot.get_updates方法的具体用法?Python TelegramBot.get_updates怎么用?Python TelegramBot.get_updates使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类twx.botapi.TelegramBot
的用法示例。
在下文中一共展示了TelegramBot.get_updates方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: MessageServer
# 需要导入模块: from twx.botapi import TelegramBot [as 别名]
# 或者: from twx.botapi.TelegramBot import get_updates [as 别名]
class MessageServer(object):
def __init__(self):
self.thread_map = {}
self.bot = TelegramBot(API_TOKEN)
self.updates = set(self.bot.get_updates().wait())
def poll(self):
while True:
del_list = []
for name in self.thread_map:
thread = self.thread_map[name]
if thread.finished_event.isSet():
del_list.append(name)
for x in del_list:
del self.thread_map[x]
print("<{time}> Waiting....".format(time=datetime.now().time()))
updates = set(self.bot.get_updates().wait())
new_updates = updates.difference(self.updates)
for update in new_updates:
print("<{time}> Received new message....".format(time=datetime.now().time()))
user = update.message.sender.id
if user in self.thread_map:
print("<{time}> Dispatching message to thread....".format(time=datetime.now().time()))
self.thread_map[user]._add_to_queue(update.message.text)
else:
print("<{time}> Creating new thread....".format(time=datetime.now().time()))
user_thread = Worker(user)
self.thread_map[user] = user_thread
print("<{time}> Dispatching message to thread....".format(time=datetime.now().time()))
user_thread._add_to_queue(update.message.text)
self.updates.add(update)
示例2: main
# 需要导入模块: from twx.botapi import TelegramBot [as 别名]
# 或者: from twx.botapi.TelegramBot import get_updates [as 别名]
def main():
try:
with open('API_KEY', 'r') as f:
api_key = f.read().replace('\n', '')
except IOError:
print "please write the api key in file `API_KEY`"
exit(1)
bot = TelegramBot(api_key)
bot.update_bot_info().wait()
print(bot.username)
last_update_id = int(0)
while True:
try:
updates = bot.get_updates(offset=last_update_id+1, timeout=5).wait()
for update in updates:
last_update_id = update.update_id
#print(update)
process_update(bot, update)
except KeyboardInterrupt:
# Allow ctrl-c.
raise KeyboardInterrupt
except Exception as e:
print "---\nException: "
print e
traceback.print_exc()
pass
示例3: main
# 需要导入模块: from twx.botapi import TelegramBot [as 别名]
# 或者: from twx.botapi.TelegramBot import get_updates [as 别名]
def main():
print '[+] Starting bot...'
# Read the config file
print '[+] Reading config file...'
config = ConfigParser.ConfigParser()
config.read([os.path.expanduser('./config')])
# Read data
bot_name = config.get('bot', 'name')
bot_token = config.get('bot', 'token')
cool_answers_raw = config.get('phrases', 'cool_answers')
cool_answers = [ answer for answer in cool_answers_raw.split('"') if answer and answer!=',']
# Last mssg id:
last_id = int(load_last_id())
print '[+] Last id: %d' % last_id
# Configure regex
regex = re.compile('[%s]' % re.escape(string.punctuation))
# Create bot
print '[+] Connecting bot...'
bot = TelegramBot(bot_token)
bot.update_bot_info().wait()
print '\tBot connected! Bot name: %s' % bot.username
while True:
try:
updates = bot.get_updates(offset=last_id).wait()
for update in updates:
id = update.message.message_id
update_id = update.update_id
user = update.message.sender
chat_id = update.message.chat.id
text = update.message.text
if int(update_id) > last_id:
last_id = update_id
save_last_id(last_id)
save_log(id, update_id, chat_id, text)
#text = regex.sub('', text)
words = text.split()
for word in words:
# Process commands:
if 'http://' in word or 'https://' in word:
# Get a random answer phrase:
answer = random.choice(cool_answers)
bot.send_message(chat_id, answer)
except (KeyboardInterrupt, SystemExit):
print '\nkeyboardinterrupt caught (again)'
print '\n...Program Stopped Manually!'
raise
示例4: YoutubeBot
# 需要导入模块: from twx.botapi import TelegramBot [as 别名]
# 或者: from twx.botapi.TelegramBot import get_updates [as 别名]
class YoutubeBot(object):
api_token = ''
def __init__(self):
self.bot = TelegramBot(self.api_token)
self.bot.get_me()
last_updates = self.bot.get_updates(offset=0).wait()
try:
self.last_update_id = list(last_updates)[-1].update_id
except IndexError:
self.last_update_id = None
print 'last update id: {}'.format(self.last_update_id)
def process_message(self, message):
text = message.message.text
chat = message.message.chat
text = text.strip().split('&')[0]
msg = 'Could not download {}'.format(text)
print 'Got message: \33[0;32m{}\33[0m'.format(text)
try:
self.bot.send_message(chat.id, 'Staring to download')
with youtube_dl.YoutubeDL(YDL_OPTS) as ydl:
r_code = ydl.download([text])
if r_code == 0:
msg = '{} download successfully'.format(text)
except Exception:
pass
self.bot.send_message(chat.id, msg)
def run(self):
print 'Main loop started'
while True:
updates = self.bot.get_updates(
offset=self.last_update_id).wait()
try:
for update in updates:
if update.update_id > self.last_update_id:
self.last_update_id = update.update_id
self.process_message(update)
except Exception as ex:
print traceback.format_exc()
示例5: Telegram
# 需要导入模块: from twx.botapi import TelegramBot [as 别名]
# 或者: from twx.botapi.TelegramBot import get_updates [as 别名]
class Telegram(object):
def __init__(self, config, interpreter):
super().__init__()
self.__interpreter = interpreter
self.__logger = logging.getLogger('telegram')
logHandler = StreamHandler()
logHandler.setLevel(logging.DEBUG)
self.__logger.addHandler(logHandler)
self.__bot = TelegramBot(config['Telegram']['token'])
self.__logger.warning("Bot details: " + str(self.__bot.get_me().wait()))
self.__updateOffset = None
def send_msg(self, telegram_id, text):
self.__bot.send_message(telegram_id, text).wait()
def getUpdates(self, dbSession):
updates = None
try:
if self.__updateOffset is not None:
updates = self.__bot.get_updates(offset=self.__updateOffset + 1).wait()
else:
updates = self.__bot.get_updates().wait()
if updates is None:
raise Exception("No updates have been received due to an error")
except:
return
for update in updates:
if hasattr(update, 'message'):
self.__logger.warning(str(update.message.sender) + ": " + update.message.text)
self.__interpreter.interpret(dbSession, self, update.message.sender, update.message.text.split(' '))
if hasattr(update, 'update_id'):
self.__updateOffset = update.update_id
def shutdown(self):
pass
示例6: telebot
# 需要导入模块: from twx.botapi import TelegramBot [as 别名]
# 或者: from twx.botapi.TelegramBot import get_updates [as 别名]
def telebot(news):
"""
This Telegram bot sends a message about stock news to a user using
TWX bot library. More about this library may be find at:
https://pythonhosted.org/twx/twx/botapi/botapi.html#module-twx.botapi
"""
bot = TelegramBot('182387487:AAGiA489MZtosNOkhLjzo3_6l7xCYkG4N5A')
bot.update_bot_info().wait()
updates = bot.get_updates().wait()
for update in updates:
user_id, = re.findall("sender=User.id=(\d+)", str(update))
if user_id not in users:
users.append(user_id)
for user in users:
user_id = int(user)
bot.send_message(user_id, news)
示例7: main
# 需要导入模块: from twx.botapi import TelegramBot [as 别名]
# 或者: from twx.botapi.TelegramBot import get_updates [as 别名]
def main():
try:
with open('API_KEY', 'r') as f:
api_key = f.read().replace('\n', '')
except IOError:
print "please write the api key in file `API_KEY`"
exit(1)
bot = TelegramBot(api_key)
bot.update_bot_info().wait()
print(bot.username)
last_update_id = int(0)
last_fortune = (datetime.now() - timedelta(minutes=31))
while True:
try:
updates = bot.get_updates(offset=last_update_id+1, timeout=5).wait()
for update in updates:
last_update_id = update.update_id
print(update)
process_update(bot, update)
global rems
for rem in rems:
if rem.when < datetime.now():
bot.send_message(rem.chatid, "=== RAPPEL ===\n\n" +
unicode(rem.what))
print "removing reminder " + str(rem.id)
rems = [r for r in rems if r.id != rem.id]
print "rems = " + str(rems)
odd = random.randint(0, 100)
thirty_minutes = (datetime.now() - datetime.timedelta(minutes=5))
if last_fortune < thirty_minutes and 50 < odd:
last_fortune = datetime.datetime.now()
msg = subprocess.check_output("fortune") + ' #fortune'
bot.send_message(update.message.chat.id, msg)
except KeyboardInterrupt:
# Allow ctrl-c.
raise KeyboardInterrupt
except Exception as e:
print "---\nException: "
print e
traceback.print_exc()
pass
示例8: main
# 需要导入模块: from twx.botapi import TelegramBot [as 别名]
# 或者: from twx.botapi.TelegramBot import get_updates [as 别名]
def main():
try:
with open('API_KEY', 'r') as f:
api_key = f.read().replace('\n', '')
except IOError:
print "please write the api key in file `API_KEY`"
exit(1)
bot = TelegramBot(api_key)
bot.update_bot_info().wait()
print(bot.username)
last_update_id = int(0)
while True:
try:
updates = bot.get_updates(offset=last_update_id+1, timeout=5).wait()
for update in updates:
last_update_id = update.update_id
print(update)
process_update(bot, update)
global rems
for rem in rems:
if rem.when < datetime.now():
bot.send_message(rem.chatid, "=== RAPPEL ===\n\n" +
unicode(rem.what))
print "removing reminder " + str(rem.id)
rems = [r for r in rems if r.id != rem.id]
print "rems = " + str(rems)
except KeyboardInterrupt:
# Allow ctrl-c.
raise KeyboardInterrupt
except Exception as e:
print "---\nException: "
print e
traceback.print_exc()
pass
示例9: TelegramBot
# 需要导入模块: from twx.botapi import TelegramBot [as 别名]
# 或者: from twx.botapi.TelegramBot import get_updates [as 别名]
from twx.botapi import TelegramBot
token = '<>'
bot = TelegramBot(token)
while True:
updates = bot.get_updates().wait()
for update in updates:
if update.message.text.startswith('/start'):
bot.send_message(update.message.chat.id, 'test message body')
示例10: BotServer
# 需要导入模块: from twx.botapi import TelegramBot [as 别名]
# 或者: from twx.botapi.TelegramBot import get_updates [as 别名]
class BotServer(object):
TORRENT = {
"category": {
"movies": CATEGORY.MOVIES,
"tv": CATEGORY.TV,
"music": CATEGORY.MUSIC,
"books": CATEGORY.BOOKS,
"games": CATEGORY.GAMES,
"applications": CATEGORY.APPLICATIONS,
"xxx": CATEGORY.XXX,
},
"order": {
"size": ORDER.SIZE,
"files_count": ORDER.FILES_COUNT,
"time_add": ORDER.AGE,
"seeders": ORDER.SEED,
"leechers": ORDER.LEECH,
"asc": ORDER.ASC,
"desc": ORDER.DESC,
},
}
MODES = ["torrent.search"]
def __init__(self):
self.bot = TelegramBot(API_TOKEN)
self.updates = set(bot.get_updates().wait())
self.users_mode = {}
self.thread = Thread(target=self.call_factory)
def call_factory(self):
pass
@staticmethod
def isqrt(n):
print(n)
x = n
y = (x + 1) // 2
last_x = x
while y < x:
x = y
y = (x + n // x) // 2
last_x = x
print(last_x + 1)
return last_x + 1
def search_torrent(self, search_term, options):
page = 1
category = None
order = None
for option, value in options:
if option.split("-")[0] == "page":
page = value
elif option.split("-")[0] == "category":
category = self.TORRENT["category"][value]
elif option.split("-")[0] == "order":
order = self.TORRENT["order"][value]
torrents = Search(search_term, page=page, category=category, order=order)
return torrents
def download_torrent(self, number, torrents):
torrent = torrents[int(number)]
print(torrent["magnet_link"])
def build_keyboard(self, xy, iterable_obj):
print("Building Base keyboard")
keyboard = []
count = 0
r_count = 0
len_itter = len(iterable_obj)
print("Building Custom keyboard")
for row in range(xy):
c_count = 0
print(keyboard)
print(r_count)
keyboard.append([])
for col in range(xy):
if count < len_itter:
keyboard[r_count].append(count)
# for i, x in enumerate(iterable_obj):
# if i == count:
# print("Modifying keyboard at %s, %s from value %s" % (r_count, c_count, x))
# keyboard[r_count][c_count] = x['name']
count += 1
c_count += 1
r_count += 1
return keyboard
def build_message(self, style, result, _id=None):
if _id:
if style == "torrent.search":
print("Building Message")
msg = "We have found several torents for you.\nThey are:\n%s\n\nPleas" % "\n".join(
[str(i) + ". %s" % x.name for i, x in enumerate(result)]
)
print("Building keyboard")
keyboard = self.build_keyboard(self.isqrt(len(result)), result)
print("Building Markup")
pprint(keyboard)
#.........这里部分代码省略.........
示例11: __init__
# 需要导入模块: from twx.botapi import TelegramBot [as 别名]
# 或者: from twx.botapi.TelegramBot import get_updates [as 别名]
class DevopsBot:
def __init__(self):
self.bot=None
self.conn=None
self.c=None
self.queue=Queue()
self.keyboard = []
self.row = []
self.items_in_row = 3
# Set keyboard buttons from commands.allowable_commands list
for key in commands.allowable_commands.keys():
self.row.append(key)
if len(self.row) == self.items_in_row:
self.keyboard.append(self.row)
self.row = []
self.reply_markup = ReplyKeyboardMarkup.create(self.keyboard)
# Initialize bot
# self.bot = TelegramBot('162715180:AAFvQCJjdpws6T3lp45t8svt9X-ENVd_zwo')
self.bot = TelegramBot('172231085:AAHdG-B_ch2RTRXIupshiBpPqf7j21XLCik')
self.bot.update_bot_info().wait()
def _monitor():
print("Monitor")
def _listen():
print("Listen")
def new_user(self, name, lastname, userid):
# Insert a row of data
strr="INSERT INTO Telegram VALUES (\""+name+"\",\""+lastname+"\",\""+str(userid)+"\")"
print(strr)
# Save (commit) the changes
try:
self.c.execute(strr)
self.conn.commit()
self._send_message(userid, "Welcome, "+name+" "+lastname)
except Exception as e:# sqlite3.IntegrityError:
print(e)
self._send_message(userid, "Thanks, "+name+" "+lastname+". No need to reregister")
def handle_messages(self):
# Initialize DB
self.conn = sqlite3.connect('telegram.db')
self.c = self.conn.cursor()
# Create tables
self.c.execute('''create table if not exists Telegram (name STRING, last_name STRING, userid STRING UNIQUE)''')
while True:
print ("Waiting for message in queue")
message = self.queue.get()
user_info = message[1]
user_id = user_info[0]
first_name = user_info[1]
last_name = user_info[2]
if last_name is None:
last_name = "N/A"
print ("Got and handle message "+str(message.text))
res="Command not understood"
try:
#Extract the command
cmd_list = message.text.split()
if str(message.text) == "/start":
self.new_user(first_name, last_name, user_id)
continue
#Replace protocol command with OS command
cmd = commands.allowable_commands[cmd_list[0]]
cmd_list[0] = cmd
runner = Command(cmd_list)
runner.run(5)
print("RES "+str(runner.res)+" /RES")
self._send_message(message.sender.id, runner.res)
except Exception as e:
print ("Except: "+str(e))
def _send_message(self, uid, message):
self.bot.send_message(int(uid), message, reply_markup=self.reply_markup)
def listen(self):
offset=0
while (True):
updates = self.bot.get_updates(offset).wait()
for cnt,update in enumerate(updates):
offset=update.update_id+1
print("Putting message: "+str(update.message.text))
self.queue.put(update.message)
示例12: SmartHomeBot
# 需要导入模块: from twx.botapi import TelegramBot [as 别名]
# 或者: from twx.botapi.TelegramBot import get_updates [as 别名]
class SmartHomeBot(AbstractServiceClass):
def __init__ (self, serviceName, logLevel):
super(SmartHomeBot, self).__init__(serviceName, logLevel)
self.lastUpdateID = 0
self.validUsers = []
self.keyboards = { #"start": [["Rooms" , "All Devices"], ["Switch off all devices", "Rules"]],
"start": [["Rooms" , "All Devices"], ["Switch off all devices"]],
"Rooms": [],
"All Devices": [] ,
"Rules": []}
self.keybordForUsers = {}
self.allDevicesList = {}
self.alldevicesFunctionsList = {}
self.allRoomsList = {}
self.upnp = miniupnpc.UPnP()
self.upnp.discoverdelay = 200
self.minUPnPPort = 1024
self.maxUPnPPort = self.minUPnPPort + 20
def stop(self):
super(SmartHomeBot, self).stop()
# Starts the communication with the bot
def start(self):
self.logger.info("%s started" % self.serviceName)
self.retrieveHomeSettings()
if (self.botToken is None):
self.logger.error ("The Telegram Token is not valid")
self.stop()
else:
self.bot = TelegramBot(self.botToken)
self.homeUpdateThread = Thread (target = self.homeUpdate)
self.homeUpdateThread.start()
# serving clients
try:
while self.isRunning:
try:
#The get_updates method returns the earliest 100 unconfirmed updates
updates = self.bot.get_updates(offset = self.lastUpdateID + 1).wait()
if (updates is not None):
cont1=len(updates)
if cont1 != 0:
replyThread = Thread (target = self.reply, args=[updates[-1]])
replyThread.start()
self.lastUpdateID = updates[-1].update_id
time.sleep(1)
except Exception, e:
self.logger.error('Something wrong occurred in telegram communication: %s. restoring the bot' % (e))
self.bot = TelegramBot(self.botToken)
except KeyboardInterrupt:
self.stop()
def makeKeyboards(self):
# Rooms keyboard
keyboard = []
keyoardRow = []
self.allRoomsList = {}
for count, room in enumerate(self.myhome["rooms"]):
if ((count+1) % 3 != 0):
label = "%s - %s" % (room["roomID"], room["description"])
keyoardRow.append (label)
self.allRoomsList[label] = room
else:
label = "%s - %s" % (room["roomID"], room["description"])
keyoardRow.append (label)
keyboard.append(keyoardRow)
keyoardRow = []
self.allRoomsList[label] = room
toBeAppend = False
if (len(keyboard[-1:]) % 3 != 0 ):
keyoardRow.append ("Back")
toBeAppend = True
else:
keyoardRow.append ("Back")
keyboard.append(keyoardRow)
keyoardRow = []
toBeAppend = False
if (len(keyboard[-1:]) % 3 != 0 ):
keyoardRow.append ("Start")
toBeAppend = True
else:
keyoardRow.append ("Start")
keyboard.append(keyoardRow)
keyoardRow = []
toBeAppend = False
if (toBeAppend):
keyboard.append(keyoardRow)
#.........这里部分代码省略.........
示例13: __init__
# 需要导入模块: from twx.botapi import TelegramBot [as 别名]
# 或者: from twx.botapi.TelegramBot import get_updates [as 别名]
class DevopsBot:
authenticated = False
auth_token = None
MESSAGE_TYPE_START = "/start"
def __init__(self):
self.bot=None
self.conn=None
self.c=None
self.mem_alert = False
self.disk_alert = False
# Initialize DB
self.conn = sqlite3.connect('telegram.db')
self.c = self.conn.cursor()
# Create tables
self.c.execute('''create table if not exists Telegram (name STRING, last_name STRING, userid STRING UNIQUE)''')
# Initialize bot
self.bot = TelegramBot('TELEGRAM_BOT_UNIQUE_ID_GOES_HERE')
self.bot.update_bot_info().wait()
def new_user(self, name, lastname, userid):
# Insert a row of data
print "DEBUG: %s , %s , %s " % (name , lastname, userid)
strr="INSERT INTO Telegram VALUES (\""+name+"\",\""+lastname+"\",\""+str(userid)+"\")"
print(strr)
# Save (commit) the changes
try:
self.c.execute(strr)
self.conn.commit()
self._send_message(userid, "Welcome, "+name+" "+lastname)
except:# sqlite3.IntegrityError:
self._send_message(userid, "Thanks, "+name+" "+lastname+". No need to reregister")
def _subproc_run(self, cmd, decode=True):
print(cmd)
log = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
if not decode:
return log.communicate()[0]
return log.communicate()[0].strip()
def _handle_message(self,message):
print(str(message.text))
if message.text == self.MESSAGE_TYPE_START:
from random import randint
rand_seed = randint(1000, 1999)
send_factor.two_factor_authenticate(rand_seed, str(message.sender.id))
self._send_message(message.sender.id, "Please enter the number token your received via SMS")
self.auth_token = str(rand_seed)
return
if not self.authenticated and message.text.isdigit():
if self.auth_token == message.text:
self.new_user(message.sender.first_name, message.sender.last_name, message.sender.id)
self.authenticated = True
return
else:
self._send_message(message.sender.id, 'Wrong token, try again.')
return
if not self.authenticated:
if message.sender.id in self._get_users_list():
self.authenticated = True
else:
self._send_message(message.sender.id, "Please authenticate using /start first.")
return
res="Command not understood"
try:
cmd_list = message.text.split()
print(cmd_list)
print(cmd_list[0])
print(commands.allowable_commands)
cmd = commands.allowable_commands[cmd_list[0]]
cmd_list[0] = cmd
print "DEBUG: %s" % cmd
print("FINAL:"+cmd+"END")
res = self._subproc_run(cmd_list)
self._send_message(message.sender.id, res)
except:
self._send_message(message.sender.id, res)
def _send_message(self, uid, message):
self.bot.send_message(int(uid), message)
def operation_loop(self):
offset=0
while (True):
print(offset)
updates = self.bot.get_updates(offset).wait()
for cnt,update in enumerate(updates):
self._handle_message(update.message)
offset=update.update_id+1
self._fire_alert()
def _get_users_list(self):
userslist = []
self.c.execute("SELECT userid FROM Telegram")
for row in self.c.fetchall():
userslist.append(row[0])
#.........这里部分代码省略.........
示例14: open
# 需要导入模块: from twx.botapi import TelegramBot [as 别名]
# 或者: from twx.botapi.TelegramBot import get_updates [as 别名]
with open('.tokenfile') as inf:
API_TOKEN = inf.readline().split('=')[1]
print API_TOKEN
bot = TelegramBot(API_TOKEN)
print(bot.update_bot_info().wait())
print(bot)
print "I am a bot : " + str(bot.username)
what_i_can_do = ['/start', '/size']
initial_offset = 0
offsets = []
while offsets == []:
updates = bot.get_updates(offset=initial_offset).wait()
for update in updates:
offsets.append(update.update_id)
chat_start_offset = max(offsets) + 1
def reply_to_chat(bot, chat_id, with_message=''):
result = bot.send_message(chat_id, with_message).wait()
return result
def get_dir_size(hdfs_dir):
with open('size.csv') as inf:
for line in inf:
if line.startwith(hdfs_dir + ','):
return line.split(',')[1]
示例15: TelegramBot
# 需要导入模块: from twx.botapi import TelegramBot [as 别名]
# 或者: from twx.botapi.TelegramBot import get_updates [as 别名]
"""
bot = TelegramBot('173036865:AAGTS4HpLglqlLULSG3odoeYZr87d2GG9U0')
print bot
bot.update_bot_info().wait()
last_id = 0
print(bot.username)
TELEGRAM_MSGID=0;
TELEGRAM_MSG=1;
"""
Send a message to a user
"""
#create objects first
updates = bot.get_updates(offset= last_id, timeout=600).wait()
msg = updates[len(updates)-1][TELEGRAM_MSG]
#result = bot.send_message(user_id, 'test message body').wait()
#print(result)
"""
Get updates sent to the bot
"""
pmsg = 'jbufs'
while True:
updates = bot.get_updates(offset= last_id, timeout=600).wait()
#for update in updates:
# print(update[TELEGRAM_MSGID])