本文整理汇总了Python中twx.botapi.TelegramBot.update_bot_info方法的典型用法代码示例。如果您正苦于以下问题:Python TelegramBot.update_bot_info方法的具体用法?Python TelegramBot.update_bot_info怎么用?Python TelegramBot.update_bot_info使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类twx.botapi.TelegramBot
的用法示例。
在下文中一共展示了TelegramBot.update_bot_info方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: setupBot
# 需要导入模块: from twx.botapi import TelegramBot [as 别名]
# 或者: from twx.botapi.TelegramBot import update_bot_info [as 别名]
def setupBot(apitoken):
"""
Setup the bot
"""
bot = TelegramBot(apitoken)
bot.update_bot_info().wait()
return bot
示例2: main
# 需要导入模块: from twx.botapi import TelegramBot [as 别名]
# 或者: from twx.botapi.TelegramBot import update_bot_info [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 update_bot_info [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: start
# 需要导入模块: from twx.botapi import TelegramBot [as 别名]
# 或者: from twx.botapi.TelegramBot import update_bot_info [as 别名]
def start():
bot = TelegramBot(token)
bot.update_bot_info().wait()
print(bot.username)
#foto belle -33909375
#user_id = int(23263342)
#result = bot.send_message(user_id, 'Salve ragazzi').wait()
#XXX WebHook automatico non funzionante
result = bot.set_webhook(token)
print('*****Il risultato:' % (result))
return "ok"
示例5: TelegramBroadcaster
# 需要导入模块: from twx.botapi import TelegramBot [as 别名]
# 或者: from twx.botapi.TelegramBot import update_bot_info [as 别名]
class TelegramBroadcaster():
"""
Setup the bot
"""
def __init__(self):
self.bot = TelegramBot('<BOT_KEY>')
self.bot.update_bot_info().wait()
self.user_id = int(<CHANNEL_KEY>) # channel goyanglib
print(self.bot.username)
def send(self, message):
result = self.bot.send_message(self.user_id, message).wait()
print(result)
示例6: update
# 需要导入模块: from twx.botapi import TelegramBot [as 别名]
# 或者: from twx.botapi.TelegramBot import update_bot_info [as 别名]
def update():
bot = TelegramBot(token)
bot.update_bot_info().wait()
if 'chat' in request.json['message']:
chat = request.json['message']['chat']['id']
if 'text' in request.json['message']:
text = request.json['message']['text']
if text.find('vice') != -1:
bot.send_message(chat, vice()).wait()
if text.find('drink') != -1:
bot.send_photo(chat,bill()).wait()
#Print in console for fast Debugging
print(json.dumps(request.json))
return "ok"
示例7: telebot
# 需要导入模块: from twx.botapi import TelegramBot [as 别名]
# 或者: from twx.botapi.TelegramBot import update_bot_info [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)
示例8: main
# 需要导入模块: from twx.botapi import TelegramBot [as 别名]
# 或者: from twx.botapi.TelegramBot import update_bot_info [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
示例9: main
# 需要导入模块: from twx.botapi import TelegramBot [as 别名]
# 或者: from twx.botapi.TelegramBot import update_bot_info [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
示例10: main
# 需要导入模块: from twx.botapi import TelegramBot [as 别名]
# 或者: from twx.botapi.TelegramBot import update_bot_info [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')
user_id = config.get('user', 'allowed')
# 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
# Create media player controllers:
player = MediaPlayer()
if not player.connect_to_player():
print 'Error connecting to player. Exiting...'
return -1
# Send special keyboard:
send_keyboard(bot, user_id)
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 word == '/start':
print "New user started the app: " + str(user)
# Restricted API
if int(user_id) == user.id:
if 'Play' in word:
print '[+] Play command'
player.play()
elif 'Pause' in word:
print '[+] Pause command'
player.pause()
elif 'Previous' in word:
print '[+] Previous command'
player.previous()
elif 'Next' in word:
print '[+] Next command'
player.next()
except (KeyboardInterrupt, SystemExit):
print '\nkeyboardinterrupt caught (again)'
print '\n...Program Stopped Manually!'
raise
示例11: __init__
# 需要导入模块: from twx.botapi import TelegramBot [as 别名]
# 或者: from twx.botapi.TelegramBot import update_bot_info [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: __init__
# 需要导入模块: from twx.botapi import TelegramBot [as 别名]
# 或者: from twx.botapi.TelegramBot import update_bot_info [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])
#.........这里部分代码省略.........
示例13: main
# 需要导入模块: from twx.botapi import TelegramBot [as 别名]
# 或者: from twx.botapi.TelegramBot import update_bot_info [as 别名]
def main():
prewarning_counter=0
warning_counter=0
alert_counter=0
day_alert_flag=False
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')
#user_id=[]
#user_id.append(config.get('user', 'allowed'))
#for x in user_id:
# print(x)
#misiones.append(nuevo_elemento)
user_id= config.get('user', 'allowed')
# 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 '[+] Conectando tu bot...'
bot = TelegramBot(bot_token)
bot.update_bot_info().wait()
print '\tBot conectado! El nombre de tu bot es: %s' % bot.username
# Send special keyboard:
send_keyboard(bot, user_id)
print bot
global chat_id
chat_id=[]
while True:
try:
updates = bot.get_updates(offset=last_id).wait()
#print updates[0].message.sender
#print "-------------------------------"
time_notify=t.asctime(t.localtime(t.time()) )
#print(time_notify)
time_notify=time_notify.split(" ");
#print(time_notify)
main_hour=time_notify[3]
main_hour=main_hour.split(":")
main_hour=map(int, main_hour)
#print(main_hour)
for update in updates:#arroja un error de tiempo
id = update.message.message_id
update_id = update.update_id
user = update.message.sender
#file_chat_id=open('chat_id.txt','r')
#chat_id_aux=file_chat_id.read()
#print(chat_id_aux)
#chat_id.append(update.message.chat.id)
#for x in chat_id:
# print (x)
active_chat_id = update.message.chat.id
#chat_id=8999128
#chat_id2=97335854
text = update.message.text
#if main_hour[0]==00 and main_hour[1]==00 and main_hour[2]==00:#Reset the day_alert_flag
#if main_hour[2]==50:#Reset the day_alert_flag
#day_alert_flag=False
#print("FLAG RESETEADA A FALSE")
if (main_hour[0]==9 and main_hour[1]==30 and main_hour[2]==00) or (main_hour[0]==12 and main_hour[1]==30 and main_hour[2]==00) or (main_hour[0]==14 and main_hour[1]==30 and main_hour[2]==00) :
#if main_hour[2]==00: #and main_hour[2]==00 :# and main_hour[2]==00:
#day_alert_flag=True #This day the alert is done
#Acceso al html
d = pq(url='http://www.mambiente.munimadrid.es/opencms/opencms/calaire/consulta/Gases_y_particulas/informegaseshorarios.html?__locale=es')
#Selection of data date
date_data=d('span[class=tabla_titulo_fecha]')
date_data=date_data.text()
#print (date_data)
#Selection of station name
station_name=d('td[class="primertd"]')
station_name=station_name.append("**")
#.........这里部分代码省略.........
示例14: open
# 需要导入模块: from twx.botapi import TelegramBot [as 别名]
# 或者: from twx.botapi.TelegramBot import update_bot_info [as 别名]
from twx.botapi import TelegramBot
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 + ','):
示例15: RepeaterStatusBot
# 需要导入模块: from twx.botapi import TelegramBot [as 别名]
# 或者: from twx.botapi.TelegramBot import update_bot_info [as 别名]
class RepeaterStatusBot(object):
def __init__(self, tg_group, tg_credentials,
repeater_info_url, repeater_json_stream_url):
self.logger = logging.getLogger(__name__)
self.tg_group = tg_group
self.tg_credentials = tg_credentials
self.repeater_json_stream_url = repeater_json_stream_url
self.repeater_info_url = repeater_info_url
self.rx_status = {}
self.statuses = {
True: 'in',
False: 'uit',
}
self.last_updated = datetime(1970, 1, 1)
self.RXes = {}
self.update_rxes()
self.last_message_send = datetime(1970, 1, 1)
self._init_telegram()
def _init_telegram(self):
self.telegram = TelegramBot(self.tg_credentials)
self.telegram.update_bot_info().wait()
def update_rxes(self):
if datetime.now() - self.last_updated > timedelta(minutes=60):
self.logger.info('Updating repeater info')
try:
repeater_info = requests.get(self.repeater_info_url).json()
except ValueError:
repeater_info = {}
self.last_updated = datetime.now()
self.RXes = repeater_info.get('rx', {})
def signal_telegram(self, message, retry=3):
self.logger.info('Sending via TGL: {msg}'.format(msg=message))
if retry < 1:
self.logger.error('Failed sending message, exceeded retries')
return False
try:
result = self.telegram.send_message(self.tg_group, message).wait()
if not result:
new_retry = retry - 1
self.signal_telegram(message, retry=new_retry)
else:
return True
except Exception as error:
self.logger.error('Caught exception while transmitting message: {type}: {message}'.format(
type=type(error),
message=str(error)
))
self._init_telegram()
new_retry = retry - 1
return self.signal_telegram(message, retry=new_retry)
def queue_message(self, receiver, enabled):
if receiver in self.RXes:
receiver = self.RXes[receiver]['name']
msg = '"{receiver} is {status}geschakeld"'.format(
receiver=receiver, status=self.statuses[enabled]
)
self.logger.info('Queueing: {msg}'.format(msg=msg))
result = self.signal_telegram(msg)
def run(self):
for line in requests.get(self.repeater_json_stream_url,
stream=True).iter_lines(1):
self.logger.debug('Received: {data}'.format(data=line))
if line.startswith('data: '):
data = line.split('data: ')[1].strip()
try:
line_json = json.loads(data)
except Exception as e:
self.logger.warn('FAILED (%s): %s', data, e.message)
else:
self.update_rxes()
if line_json.get('event') == 'Voter:sql_state':
for rx in line_json.get('rx', []).keys():
if rx not in self.rx_status:
self.rx_status[rx] = None
status = line_json['rx'][rx]['sql'] != "off"
if self.rx_status[rx] is not None and \
self.rx_status[rx] != status:
self.queue_message(rx, status)
self.rx_status[rx] = status