def main(argv=sys.argv[1:]): argument_parser = argparse.ArgumentParser() # argument_parser.add_argument('--username', type=str, # default='PiazzaBot', help='the bot\'s Keybase username') args = argument_parser.parse_args(argv) logger.info('keybase_piazza_bot starting') event_loop = asyncio.get_event_loop() piazza = Piazza() piazza.user_login() # login prompt cse220 = piazza.network(PIAZZA_NETWORK_ID) keybase_bot_handler = KeybaseBotHandler(piazza, cse220) keybase_bot = Bot( handler=keybase_bot_handler, loop=event_loop, # username=args.username, ) future = keybase_bot.start({}) event_loop.run_until_complete(future) event_loop.close() logger.info('keybase_piazza_bot exiting')
def setup(config): if config.sentry_dsn: sentry_sdk.init(config.sentry_dsn) database.setup(config.db) import nltk libs = ('punkt', 'averaged_perceptron_tagger', 'universal_tagset') for lib in libs: nltk.download(lib, quiet=True) return Bot(username=config.username, handler=Handler(config))
def setup_bot_with_name(name): nonlocal bot bot = Bot( username=config["bots"][name]["username"], paperkey=config["bots"][name]["paperkey"], handler=noop_handler, home_path=tmpdir, keybase=kb_destination, ) return bot
async def make_a_poll(): channel = chat1.ChatChannel(name="yourcompany.marketing", topic_name="lunchtalk", members_type="team") def noop_handler(*args, **kwargs): pass # you don't need to pass in a username or paperkey if you're already logged in bot = Bot(handler=noop_handler) result = await bot.chat.send(channel, "what are y'all feeling for lunch?") msg_id = result.message_id await asyncio.gather( bot.chat.react(channel, msg_id, ":burrito:"), bot.chat.react(channel, msg_id, ":sandwich:"), bot.chat.react(channel, msg_id, "other"), )
async def scrolling_message(message, before="", after=""): channel = chat1.ChatChannel(name="yourcompany.marketing", topic_name="lunchtalk", members_type="team") def noop_handler(*args, **kwargs): pass bot = Bot( # you don't need to pass in a username or paperkey if you're already logged in handler=noop_handler) result = await bot.chat.send(channel, f"{before}{message}{after}") msg_id = result.message_id while True: message = rotate(message) await bot.chat.edit(channel, msg_id, f"{before}{message}{after}") await asyncio.sleep(0.5)
async def make_a_poll(): channel = { "name": "yourcompany.marketing", "topic_name": "lunchtalk", "members_type": "team", } def noop_handler(*args, **kwargs): pass bot = Bot( username="******", # you don't need to pass in a paperkey if you're already logged in handler=noop_handler, ) resp = await bot.chat.send(channel, "what are y'all feeling for lunch?") msg_id = resp['result']['id'] await bot.chat.react(channel, msg_id, ":burrito:") await bot.chat.react(channel, msg_id, ":sandwich:") await bot.chat.react(channel, msg_id, "other")
async def simple_user(): def noop_handler(*args, **kwargs): pass bot = Bot(handler=noop_handler()) namespace = "current-favorites" key = "Sam" # using the default team, which is yourself (your implicit self-team # "yourusername,yourusername") # put with default revision # note: if revision=None, the server does a get (to get # the latest revision number) then a put (with revision # number + 1); this operation is not atomic. value = "The Left Hand of Darkness" res = await bot.kvstore.put(namespace, key, value, revision=None) print("PUT: ", res) rev = res.revision # fail put try: res = await bot.kvstore.put(namespace, key, "Fahrenheit 451", revision=rev) except RevisionError as e: print("EXPECTING PUT FAIL: ", e) # list namespaces res = await bot.kvstore.list_namespaces() print("LIST NAMESPACES: ", res) assert len(res.namespaces) > 0 # list entryKeys res = await bot.kvstore.list_entrykeys(namespace) print("LIST ENTRYKEYS: ", res) assert len(res.entry_keys) > 0 # get res = await bot.kvstore.get(namespace, key) print("GET: ", res) assert res.entry_value == value # fail delete try: res = await bot.kvstore.delete(namespace, key, revision=rev + 2) except RevisionError as e: print("EXPECTING DELETE FAIL: ", e) # delete res = await bot.kvstore.delete(namespace, key, revision=rev + 1) print("DELETE: ", res) assert res.revision == rev + 1 # fail delete try: res = await bot.kvstore.delete(namespace, key, revision=rev + 2) except DeleteNonExistentError as e: print("EXPECTING DELETE FAIL: ", e) # get res = await bot.kvstore.get(namespace, key) print("GET: ", res) assert res.entry_value == ""
conversation_id = event.msg.conv_id msg = f"`-5` points deducted from @{event.msg.sender.username} for asking me to fetch the weather.\n" \ f"https://mars.nasa.gov/layout/embed/image/insightweather/" members = await get_channel_members(conversation_id) channel_name = str(event.msg.channel.name).replace(",", "") write_score(event.msg.sender.username, members, event.msg.sender.username, channel_name, -5, team_name) await bot.chat.send(conversation_id, msg) listen_options = { "local": False, "wallet": False, "dev": True, "hide-exploding": False, "convs": True, "filter_channel": { "name": "morethanbits", "topic_name": "test", "members_type": "team" }, "filter_channels": None, } bot = Bot(username=f"{os.environ.get('KEYBASE_BOTNAME')}", paperkey=os.environ.get('KEYBASE_PAPERKEY'), handler=handler, home_path=f'./{os.environ.get("KEYBASE_BOTNAME")}') asyncio.run(bot.start(listen_options=listen_options))
async def __call__(self, bot, event): if event.msg.content.type != ContentType.TEXT: return channel = event.msg.channel if event.msg.content.text.body != "trigger": return # If you message 3 "trigger"s in rapid succession, the bot should # be done sending the alerts in ~5 seconds as opposed to 15 seconds. # BUT if you try this again with use_lock=True, it will stack the # requests and take the full 15 seconds. if self.use_lock: async with self.lock: await alert(bot, 5, channel) else: await alert(bot, 5, channel) listen_options = { 'filter-channel': {"name": "yourbot,someoneelse"} } loop = asyncio.get_event_loop() bot = Bot( username="******", paperkey=os.environ['KEYBASE_PAPERKEY'], handler=Handler(use_lock=False), loop=loop, ) loop.run_until_complete(bot.start(listen_options)) loop.close()
# print("conversation: {} messageId: {} filename: {}".format(channel.name, event.msg.id, event.msg.content)) filename = event.msg.content.attachment.object.filename os.system( "keybase chat download {channel} {attachmentId} -o {filename}" .format(channel=channel.name, attachmentId=int(event.msg.id), filename=filename)) os.system( "keybase fs cp {filename} /keybase/private/{doc},{patientName}" .format(filename=filename, doc=bot.username, patientName=channel.name.replace( bot.username + ",", ""))) os.system("del {filename}".format(filename=filename)) listen_options = { "local": True, "wallet": True, "dev": True, "hide-exploding": False, "filter_channel": None, "filter_channels": None, } bot = Bot(username="******", paperkey=os.environ.get('PAPERKEY'), handler=Handler()) asyncio.run(bot.start(listen_options))
await self.add(bot, team, issuer, secret) send_msg = "TOTP added for {}".format(issuer) except Exception as e: print(e) finally: await bot.chat.send(channel, send_msg) return async def handle_remove(self, bot, channel, team, msg, action): if len(msg) == 3: issuer = msg[2] # chat: "!totp remove <issuer>" send_msg = "No keys to remove for {}".format(issuer) try: await self.remove(bot, team, issuer) send_msg = "Removed TOTP keys for {}".format(issuer) except Exception as e: print(e) finally: await bot.chat.send(channel, send_msg) return username = "******" bot = Bot(username=username, paperkey=os.environ["KEYBASE_PAPERKEY"], handler=TotpHandler()) asyncio.run(bot.start({}))
def parse_usd_amount(amount_description): # "20.1234 XLM" => 2.614 amount_str, currency = amount_description.split() assert currency == "XLM" return float(amount_str) * DollarsPerLumen class Handler: async def __call__(self, bot, event): if event.type != EventType.WALLET: return if (event.notification.summary.status_description != stellar1.PaymentStatusStrings.COMPLETED.value): return usd = parse_usd_amount(event.notification.summary.amount_description) sender = event.notification.summary.from_username channel = chat1.ChatChannel(name=f"{bot.username},{sender}") message = "thank you so much for the ${0:.2f} :moneybag:".format(usd) await bot.chat.send(channel, message) listen_options = {"wallet": True} bot = Bot(username="******", paperkey=os.environ["KEYBASE_PAPERKEY"], handler=Handler()) asyncio.run(bot.start(listen_options))
def makeString(dict): pack_str = 'My Packages 📦\n' for key, value in dict.items(): pack_str = pack_str + key + ' : ' + value + '\n' return pack_str + '\n' async def handler(bot, event): if event.msg.content.type_name != chat1.MessageTypeStrings.TEXT.value: return msg = str(event.msg.content.text.body).lower() if keyphrase in msg: channel = event.msg.channel sender = event.msg.sender.username # print(sender) if sender == bot.username: # print(msg) return pack_str = makeString(packs) # print(pack_str) await bot.chat.send(channel, pack_str) paperkey = os.environ.get("KEYBASE_PAPERKEY") username = os.environ.get('KEYBASE_USERNAME') bot = Bot( username=username, paperkey=paperkey, handler=handler ) asyncio.run(bot.start(listen_options))
import asyncio import yaml import pykeybasebot.types.chat1 as chat1 from pykeybasebot import Bot from swagger_server.data import CONFIG, DATA from swagger_server.models.host import Host def noop_handler(*args, **kwargs): pass bot = Bot(handler=noop_handler) async def async_send(topic, message, msg_id=0): channel = chat1.ChatChannel(name=CONFIG['keybase']['TEAM'], topic_name=topic, members_type="team") if msg_id > 0: app.logger.info(f"async_send('{topic}', {msg_id}, edit '{message}')") await bot.chat.edit(channel, msg_id, message) return msg_id else: app.logger.info(f"async_send('{topic}', {msg_id}, send '{message}')") result = await bot.chat.send(channel, message)
if not team_found: bt.send_message("I don't belong here.", team=team, channel=channel) else: # Is a PM print("{} said {}".format(sender, message)) class Handler: async def __call__(self, bot, event): if event.msg.content.type != ContentType.TEXT: return else: process_kbmsg(event.msg.content.text.body, event.msg.sender.username, event.msg.channel.name, event.msg.channel.topic_name) listen_options = { 'local': True, 'wallet': True, 'dev': True, 'hide-exploding': False, 'filter_channel': None, 'filter_channels': None, } bot = Bot( username=bot_name, handler=Handler(), ) asyncio.run(bot.start(listen_options))
'UPDATE games SET status = "completed", submitted = ? WHERE id = ?', [next_key, matched_game[0]]) conn.commit() conn.close() await bot.chat.send(channel, final_results(matched_game[0])) return None next_prompt = titles[ matched_game[7]]['keys'][next_key]['Prompt'] cur.execute('UPDATE games SET submitted =? WHERE id = ?', [next_key, matched_game[0]]) conn.commit() conn.close() await bot.chat.send( channel, f'Got it! Your next prompt is:\n`{next_prompt}`') return listen_options = { "local": True, "wallet": True, "dev": True, "hide-exploding": False, "filter_channel": None, "filter_channels": None } bot = Bot(username=config['bot_name'], paperkey=config['paper_key'], handler=Handler()) asyncio.run(bot.start(listen_options=listen_options))
def new_bot() -> Bot: return Bot( username=os.environ["KEYBASE_USERNAME"], paperkey=os.environ["KEYBASE_PAPERKEY"], handler=handler, )
async def __call__(self, bot, event): async with self.lock: channel = event.msg.channel msg_id = event.msg.id if event.msg.content.type_name == 'text': if event.msg.content.text.body.startswith('!sinterklaas'): sentence = event.msg.content.text.body.split()[1:] if not sentence: sentence = ["Beste"] await bot.chat.send(channel, "Sint: even denken...") poem = get_message(" ".join(sentence)) await bot.chat.send(channel, poem) listen_options = { "local": True, "wallet": False, "dev": False, "hide-exploding": False, "convs": True, "filter_channel": None, "filter_channels": None, } bot = Bot( username=args.user, paperkey=args.key, handler=Handler() ) asyncio.run(bot.start(listen_options))
# This bot listens in one channel and reacts to every text message. ################################### import asyncio import logging from pykeybasebot import Bot, ContentType logging.basicConfig(level=logging.DEBUG) async def handler(bot, event): if event.msg.content.type != ContentType.TEXT: return channel = event.msg.channel msg_id = event.msg.id await bot.chat.react(channel.replyable_dict(), msg_id, ":clap:") listen_options = { 'filter-channel': {"name":"yourbot,someoneelse"} } bot = Bot( username="******", paperkey=os.environ['KEYBASE_PAPERKEY'], handler=handler, ) asyncio.run(bot.start(listen_options))
await bot.chat.send(channel, response) else: try: r = requests.get(event.msg.content.text.body) process_file(event.msg.content.text.body, ".html") return 0 except: return_param = print("Error encountered") if event.msg.content.type_name != chat1.MessageTypeStrings.TEXT.value: return if (event.msg.content.text.body).lower() == "hi" or (event.msg.content.text.body).lower() == "hello" or (event.msg.content.text.body).lower() == "howdy" or (event.msg.content.text.body).lower() == "hey" : channel = event.msg.channel await bot.chat.send(channel, "Salutations! What can I help you with today? (Please Attach a PDF File or Web URL for Analysis)") listen_options = { "local": True, "wallet": True, "dev": True, "hide-exploding": False, "filter_channel": None, "filter_channels": None, } bot = Bot( username="******", paperkey="popular electric common popular argue absent rate yellow always similar engine labor million", handler=Handler() ) asyncio.run(bot.start(listen_options))
import json import time import asyncio import requests from pykeybasebot import Bot import pykeybasebot.types.chat1 as chat1 from config import * attempts = {} sent = {} states = [] keybaseBot = None if KEYBASE_BOT_KEY: keybaseBot = Bot(username=KEYBASE_BOT_USERNAME, paperkey=KEYBASE_BOT_KEY, handler=None) def alert(msg): if msg in sent and time.time() - sent[msg] < SENT_TIMEOUT: return print(time.strftime("%a, %d %b %Y %H:%M:%S", time.gmtime()), msg) sent[msg] = int(time.time()) if KEYBASE_BOT_KEY: try: channel = chat1.ChatChannel(**KEYBASE_BOT_CHANNEL) asyncio.run(keybaseBot.chat.send(channel, msg)) except Exception as e: print('keybase error', e) if TELEGRAM_BOT_KEY: try:
storage(splitter) elif len(event.msg.content.text.body) < 40: wok = event.msg.content.text.body inputter = wok splitter = give() if sentencefind(inputter, splitter) == None: pass else: sentences = splitter[sentencefind(inputter, splitter)] await bot.chat.send(channel, sentences) listen_options = { "local": True, "wallet": True, "dev": True, "hide-exploding": False, "filter_channel": None, "filter_channels": None, } bot = Bot(username="******", paperkey= "identify virtual arctic hotel recall already neutral card cabin promote federal romance lend", handler=handler) asyncio.run(bot.start(listen_options))
elif query == "delete my amazon account": output = ':white_check_mark:It has been deleted.' elif query == "thanks": output = ':innocent:No worries. Have a good day!' else: output = 'Hi there! I am your fully autonomous digital assistant. Type /priv "message" to get started. Ask me "what\'s new?"' await bot.chat.send(channel, output) listen_options = { "local": True, "wallet": True, "dev": True, "hide-exploding": False, "filter_channel": None, "filter_channels": None, } key_file = open("paperkey.txt", "r+") bot = Bot(username="******", paperkey=key_file.read(), handler=Handler()) asyncio.run(bot.start(listen_options)) # Improvments: # -format for the 'most commonly refers to:' # - get rid of the [1], etc