Example #1
0
async def shitpost(conn: Connection, room: Optional[str], user: str, arg: str) -> None:
    if room is None:
        return
    message = utils.remove_accents(arg.strip())
    if len(message) > 50:
        await conn.send_reply(room, user, "Testo troppo lungo")
        return

    text0 = ""
    text1 = ""
    text2 = ""

    if message == "":
        if not utils.is_private(conn, room):
            return
        message = "SHITPOST"

    if not utils.is_private(conn, room) and ("x" in message or "X" in message):
        message = "lolno"

    for i in message:
        if i in LETTERS:
            if text0 != "":
                text0 += " "
                text1 += " "
                text2 += " "
            text0 += LETTERS[i][0]
            text1 += LETTERS[i][1]
            text2 += LETTERS[i][2]

    html = '<pre style="margin: 0; overflow-x: auto">{}<br>{}<br>{}</pre>'

    await conn.send_htmlbox(room, user, html.format(text0, text1, text2))
Example #2
0
def mode(irc, event, args):
    """[<channel>] <modes>

    Sets <modes> in <channel>. <channel> is only necessary if the command
    isn't sent in the channel itself.
    """
    try:
        if utils.is_private(event) or irc.is_channel(args[0]):
            if args[0] in irc.state["channels"]:
                channel = args[0]
                setmodes = utils.split_modes(args[1:])
            elif not utils.is_private(event):
                channel = event.target
                setmodes = utils.split_modes(args)
            else:
                irc.reply(event, utils.gethelp("mode"))
                return
        else:
            channel = event.target
            setmodes = utils.split_modes(args)

    except IndexError:
        irc.reply(event, utils.gethelp("mode"))

    else:
        if utils.is_allowed(irc, event.source, channel):
            already_op = irc.is_opped(irc.get_nick(), channel)
            if not already_op:
                setmodes.append("-o {}".format(irc.get_nick()))
            gotop = utils.getop(irc, channel)
            if gotop:
                for modes in utils.unsplit_modes(setmodes):
                    irc.mode(channel, modes)
Example #3
0
def squiet(irc, event, args):
    """[<channel>] <nick|hostmask> [<nick|hostmask>...]

    Quiets <nick> in <channel> using services. <channel> is only necessary
    if the command isn't sent in the channel itself.
    """
    try:
        if utils.is_private(event):
            channel = args[0]
            nicks = args[1:]
        else:
            if irc.is_channel(args[0]):
                channel = args[0]
                nicks = args[1:]
            else:
                channel = event.target
                nicks = args

    except IndexError:
        irc.reply(event, utils.gethelp("squiet"))

    else:
        if utils.is_allowed(irc, event.source, channel):
            try:
                if irc.channels[channel].get("chanserv", irc.chanserv):
                    irc.privmsg("ChanServ", "QUIET {} {}".format(channel, " ".join(nicks)))
            except KeyError:
                pass
Example #4
0
 def should_respond_to_message(self, message):
     if self.release == 'production' and message.author.bot:
         return False
     if message.author.id in self.blocked_users:
         return False
     if utils.is_private(message.channel):
         return True
     return self._can_post_in_guild(message)
Example #5
0
 def __init__(self, ctx):
     self.ctx = ctx
     self.has_lock = False
     if is_private(ctx.channel):
         self.lock_id = ctx.author.id
         self.lock_set = Locker.DM_LOCKS
     else:
         self.lock_id = ctx.guild.id
         self.lock_set = Locker.SERVER_LOCKS
Example #6
0
 async def on_message_discarded(self, message):
     if not message.author.bot and message.content.count(
             '$$') >= 2 and not message.content.startswith('=='):
         if is_private(message.channel) or (
                 await self.bot.settings.resolve_message('c-tex', message)
                 and await self.bot.settings.resolve_message(
                     'f-inline-tex', message)):
             latex = extract_inline_tex(message.clean_content)
             if latex != '':
                 await self.handle(message, latex, centre=False)
Example #7
0
 async def __aenter__(self):
     if self.lock_id in self.lock_set:
         # Might move this out into another function later??
         await self.ctx.send(IGNORE_MESSAGE_DM if is_private(
             self.ctx.channel) else IGNORE_MESSAGE_SERVER)
         return False
     # There is no race condition here, because between checking the lock and adding the lock, there is no way to switch coroutines and do something else.
     self.lock_set.add(self.lock_id)
     self.has_lock = True
     return True
Example #8
0
def unquiet(irc, event, args):
    """[<channel>] [<nick|hostmask>...]

    Unquiets <nick> (or yourself if no <nick> is specified) in <channel>.
    <channel> is only necessary if the command isn't sent in the channel
    itself.
    """
    setmodes = []
    try:
        if utils.is_private(event):
            channel = args[0]
            if len(args) > 1:
                nicks = args[1:]
            else:
                nicks = [event.source.nick]
        else:
            if len(args) > 0:
                if irc.is_channel(args[0]):
                    channel = args[0]
                    if len(args) > 1:
                        nicks = args[1:]
                    else:
                        nicks = [event.source.nick]
                else:
                    channel = event.target
                    nicks = args
            else:
                channel = event.target
                nicks = [event.source.nick]

    except IndexError:
        irc.reply(event, utils.gethelp("unquiet"))

    else:
        if utils.is_allowed(irc, event.source, channel):
            for nick in nicks:
                if utils.is_hostmask(nick):
                    hmask = nick
                else:
                    hmask = utils.gethm(irc, nick)
                if hmask and channel in irc.state["channels"]:
                    for bmask in irc.state["channels"][channel]["quiets"]:
                        if fnmatch(utils.irclower(hmask), utils.irclower(bmask)):
                            setmodes.append("-q {}".format(bmask))
                else:
                    return
            if len(setmodes) == 0:
                return
            already_op = irc.is_opped(irc.get_nick(), channel)
            if not already_op:
                setmodes.append("-o {}".format(irc.get_nick()))
            gotop = utils.getop(irc, channel)
            if gotop:
                for mode in utils.unsplit_modes(setmodes):
                    irc.mode(channel, mode)
Example #9
0
 async def format_adm(ctx, assuptions, small):
     embed = discord.Embed(title='Do more with Wolfram|Alpha pro',
                           url='http://www.wolframalpha.com/pro/')
     if not is_private(ctx.channel) and await ctx.bot.settings.resolve(
             'f-wolf-mention', ctx.channel, ctx.channel.guild):
         embed.add_field(name='Query made by', value=ctx.author.mention)
     if not small and assuptions and assuptions.count > 0 and len(
             str(assuptions)) <= 800:
         embed.add_field(name='Assumptions', value=str(assuptions))
         return embed, True
     return embed, False
Example #10
0
	async def allow_calc_history(self, channel):
		# if not self.bot.parameters.get('calculator.persistent'):
		# 	return False
		if self.bot.parameters.get('release') == 'development':
			return True
		if not ENABLE_HISTORY:
			return False
		if utils.is_private(channel):
			return (await self.bot.patron_tier(channel.recipient.id)) >= patrons.TIER_CONSTANT
		else:
			return (await self.bot.patron_tier(channel.guild.owner.id)) >= patrons.TIER_CONSTANT
Example #11
0
	async def handle_view_history(self, ctx):
		''' Command to view the list of recently run expressions. '''
		if not await self.allow_calc_history(ctx.channel):
			await ctx.send(HISTORY_DISABLED_PRIVATE if utils.is_private(ctx.channel) else HISTORY_DISABLED)
		else:
			commands = await self.unpack_commands(ctx.channel)
			if not commands:
				await ctx.send('No persistent commands have been run in this channel.')
			else:
				commands_text = map(lambda x: x['expression'], commands)
				for i in history_grouping(commands_text):
					await ctx.send(i)
Example #12
0
def send_broadcast_all(bot, update):
    bot.sendChatAction(chat_id=update.message.chat.id, action=telegram.ChatAction.TYPING)

    if utils.is_private(update.message) and security.is_authorized(update.message, 'admin'):
        conn = sqlite3.connect(configuration.db_users_path)
        c = conn.cursor()
        c.execute("SELECT chat_id FROM USERS WHERE chat_allowed = 1")
        rows = c.fetchall()
        for row in rows:
            if row[0] != str(update.message.chat.id):
                bot.sendMessage(chat_id=row[0], text=command_payload(update.message.text))
        conn.close()
        bot.sendMessage(chat_id=update.message.chat_id, text='Message successfully broadcasted to known users.')
Example #13
0
 async def allow_calc_history(self, channel):
     if self.bot.parameters.get('release') == 'development':
         return True
     if not ENABLE_HISTORY:
         return False
     if utils.is_private(channel):
         return (await self.bot.patron_tier(channel.recipient.id
                                            )) >= patrons.TIER_CONSTANT
     if channel.guild in HISTORY_ENABLED_SERVERS:
         return True
     if (await self.bot.patron_tier(channel.guild.owner_id
                                    )) >= patrons.TIER_CONSTANT:
         return True
     return False
Example #14
0
 async def ensure_loaded(self, channel, blame):
     # If command were previously run in this channel, re-run them
     # in order to re-load any functions that were defined
     # Ensure that only one coroutine is allowed to execute the code
     # in this block at once.
     async with self.replay_state[channel.id].semaphore:
         if not self.replay_state[channel.id].loaded:
             if ENABLE_LIBS and not utils.is_private(channel):
                 print('Loading libraries for channel', channel)
                 await self.run_libraries(channel, channel.guild)
             if ENABLE_HISTORY and await self.allow_calc_history(channel):
                 print('Replaying calculator commands for', channel)
                 await self.restore_history(channel, blame)
             self.replay_state[channel.id].loaded = True
Example #15
0
 async def advertise_to(self, user, channel, destination):
     if self.parameters.get('advertising enable') and (
             await self.patron_tier(user.id)) == patrons.TIER_NONE:
         chan_id = str(
             channel.id if is_private(channel) else channel.guild.id)
         counter = (await self.keystore.get('advert_counter', chan_id)) or 0
         interval = self.parameters.get('advertising interval')
         await self.keystore.set('advert_counter', chan_id, counter + 1)
         if counter % interval == 0:
             await destination.send(
                 embed=discord.Embed(title='Support the bot on Patreon!',
                                     description=random.choice(MESSAGES),
                                     colour=discord.Colour.blue(),
                                     url='https://www.patreon.com/dxsmiley')
             )
Example #16
0
def quiet(irc, event, args):
    """[<channel>] <nick|hostmask> [<nick|hostmask>...]

    Quiets <nick> in <channel>. <channel> is only necessary if the command
    isn't sent in the channel itself.
    """
    setmodes = []
    affected = []
    try:
        if utils.is_private(event):
            channel = args[0]
            nicks = args[1:]
        else:
            if irc.is_channel(args[0]):
                channel = args[0]
                nicks = args[1:]
            else:
                channel = event.target
                nicks = args

    except IndexError:
        irc.reply(event, utils.gethelp("quiet"))

    else:
        if utils.is_allowed(irc, event.source, channel):
            for nick in nicks:
                if utils.is_hostmask(nick):
                    bmask = nick
                else:
                    bmask = utils.banmask(irc, nick)
                setmodes.append("+q {}".format(bmask))
                for affect in utils.ban_affects(irc, channel, bmask):
                    if affect not in affected and affect != irc.get_nick():
                        affected.append(affect)
            for nick in affected:
                if irc.is_opped(nick, channel):
                    setmodes.append("-o {}".format(nick))
                if irc.is_voiced(nick, channel):
                    setmodes.append("-v {}".format(nick))
            if len(setmodes) == 0:
                return
            already_op = irc.is_opped(irc.get_nick(), channel)
            if not already_op:
                setmodes.append("-o {}".format(irc.get_nick()))
            gotop = utils.getop(irc, channel)
            if gotop:
                for mode in utils.unsplit_modes(setmodes):
                    irc.mode(channel, mode)
Example #17
0
async def quotelist(conn: Connection, room: Optional[str], user: str,
                    arg: str) -> None:
    quoteroom = arg.split(",")[0]

    db = Database()
    quotes_n = db.execute("SELECT COUNT(*) FROM quotes WHERE roomid = ?",
                          [quoteroom]).fetchone()
    if not quotes_n[0]:
        await conn.send_reply(room, user, "Nessuna quote da visualizzare.")
        return

    message = f"{conn.domain}quotes/{quoteroom}"
    if utils.is_private(conn, quoteroom):
        token_id = utils.create_token(" ", [quoteroom])
        message += f"?token={token_id}"
    await conn.send_reply(room, user, message)
Example #18
0
def kick(irc, event, args):
    """[<channel>] <nick> [<nick>...] [:][<reason>]

    Kicks <nick> in <channel>. <channel> is only necessary if the
    command isn't sent in the channel itself. It is recommended to
    use ':' as a seperator between <nick> and <reason>, otherwise, if
    there's a nick in the channel matching the first word in reason it
    will be kicked.
    """
    prepare_nicks = []
    reason = None
    try:
        if utils.is_private(event):
            channel = args[0]
            nicks = args[1:]

        else:
            if irc.is_channel(args[0]):
                channel = args[0]
                nicks = args[1:]

            else:
                channel = event.target
                nicks = args

    except IndexError:
        irc.reply(event, utils.gethelp("kick"))

    else:
        if utils.is_allowed(irc, event.source, channel):
            for nick in nicks:
                if nick in irc.state["channels"][channel]["names"] and nick not in prepare_nicks and not nick.startswith(":"):
                    prepare_nicks.append(nick)
                else:
                    reason = " ".join(nicks[len(prepare_nicks):]).lstrip(": ")
                    break
            nicks = prepare_nicks
            already_op = irc.is_opped(irc.get_nick(), channel)
            gotop = utils.getop(irc, channel)
            if gotop:
                for nick in nicks:
                    if reason:
                        irc.kick(channel, nick, reason)
                    else:
                        irc.kick(channel, nick)
                if not already_op:
                    irc.mode(channel, "-o {}".format(irc.get_nick()))
def change_users_flags(bot, update):
    bot.sendChatAction(chat_id=update.message.chat.id, action=telegram.ChatAction.TYPING)

    if utils.is_private(update.message) and security.is_authorized(update.message, 'admin'):
        tokens = update.message.text.split(' ')

        if( len(tokens) == 1):
            command_info(bot,update)
        elif( len(tokens) == 2 and tokens[1] == 'list'):
            show_users(bot,update)
        elif( len(tokens) > 2 ):
            command = tokens[0]
            userId = tokens[1]
            flagMask = tokens[2]
            update_flags(bot,update,userId,flagMask)
        else:
            command_info(bot,update)
Example #20
0
 async def on_message(self, message):
     if self.release != 'production' or not message.author.bot:
         if utils.is_private(
                 message.channel) or self._can_post_in_guild(message):
             context = await self.get_context(message)
             perms = context.message.channel.permissions_for(context.me)
             required = [
                 perms.add_reactions,
                 perms.attach_files,
                 perms.embed_links,
                 perms.read_message_history,
             ]
             if not context.valid:
                 self.dispatch('message_discarded', message)
             elif not all(required):
                 await message.channel.send(REQUIRED_PERMISSIONS_MESSAGE)
             else:
                 await self.invoke(context)
Example #21
0
def log(message):
    message_type = str(message.chat.type)[0].upper()
    #print("[" + message_type + "] Message from: " + utils.get_user_info(message) + " Content: " + str(message.text))
    conn = sqlite3.connect(configuration.db_log_path)
    c = conn.cursor()

    body = str(message.text)

    data = ()

    if utils.is_private(message):
        data = (str(message.chat.first_name), str(message.chat.last_name), str(message.chat.id), body, utils.get_timestamp(),message_type)
    elif utils.is_group(message):
        data = (str(message.from_user.first_name), str(message.from_user.last_name), str(message.from_user.id), body,utils.get_timestamp(), message_type)

    c.execute("INSERT INTO log VALUES (null,?,?,?,?,?,?)", data)

    conn.commit()
    conn.close()
Example #22
0
def sdevoice(irc, event, args):
    """[<channel>] [<nick>...]

    Devoices <nick> (or the bot if no <nick> is given) in <channel> using services.
    <channel> is only necessary if the command isn't sent in the channel itself.
    """
    try:
        if utils.is_private(event):
            channel = args[0]
            if len(args) > 1:
                nicks = args[1:]
            else:
                nicks = [irc.get_nick()]
        else:
            if len(args) > 0:
                if irc.is_channel(args[0]):
                    channel = args[0]
                    if len(args) > 1:
                        nicks = args[1:]
                    else:
                        nicks = [irc.get_nick()]
                else:
                    channel = event.target
                    nicks = args
            else:
                channel = event.target
                nicks = [irc.get_nick()]

    except IndexError:
        irc.reply(event, utils.gethelp("sdevoice"))

    else:
        if utils.is_allowed(irc, event.source, channel):
            try:
                if irc.channels[channel].get("chanserv", irc.chanserv):
                    for nick in nicks:
                        if not irc.is_voiced(nick, channel):
                            nicks.remove(nick)
                    if len(nicks) > 0:
                        irc.privmsg("ChanServ", "DEVOICE {} {}".format(channel, " ".join(nicks)))
            except KeyError:
                pass
Example #23
0
def add_me(bot, update):
    bot.sendChatAction(chat_id=update.message.chat.id, action=telegram.ChatAction.TYPING)
    if (utils.is_private(update.message)):
        conn = sqlite3.connect(configuration.db_users_path)
        c = conn.cursor()

        selectData = (str(update.message.chat.id))
        c.execute("SELECT COUNT(*) FROM USERS WHERE chat_id = ?", [selectData])
        result = int(c.fetchone()[0])
        print(result)
        if (result == 0):
            insertData = (
                str(update.message.chat.id), str(update.message.chat.first_name), str(update.message.chat.last_name),
                str(utils.get_timestamp()),
                str(utils.get_timestamp()), 0, 0, 0)
            c.execute("INSERT INTO USERS VALUES (null,?,?,?,?,?,?,?,?)", insertData)
            conn.commit()
            bot.sendMessage(chat_id=update.message.chat.id, text='Your request has been submitted.');
        else:
            bot.sendMessage(chat_id=update.message.chat.id, text='Request already submitted.');
        conn.close()
Example #24
0
async def memes(conn: Connection, room: Optional[str], user: str, arg: str) -> None:
    if room is None or not utils.is_private(conn, room):
        return

    await conn.send_message(room, random.choice(MEMES))
Example #25
0
def kban(irc, event, args):
    """[<channel>] <nick|hostmask> [<nick|hostmask>...] [:][<reason>]

    Bans <nick> in <channel> and kicks anyone affected using <reason>
    as the kick message if specified. <channel> is only necessary if
    the command isn't sent in the channel itself. It is recommended to
    use ':' as a seperator between <nick> and <reason>, otherwise, if
    there's a nick in the channel matching the first word in reason it
    will be kicked.
    """
    prepare_nicks = []
    setmodes = []
    affected = []
    reason = None
    try:
        if utils.is_private(event):
            channel = args[0]
            nicks = args[1:]

        else:
            if irc.is_channel(args[0]):
                channel = args[0]
                nicks = args[1:]

            else:
                channel = event.target
                nicks = args

    except IndexError:
        irc.reply(event, utils.gethelp("kban"))

    else:
        if utils.is_allowed(irc, event.source, channel):
            for nick in nicks:
                if nick in irc.state["channels"][channel]["names"] and nick not in prepare_nicks and not nick.startswith(":"):
                    prepare_nicks.append(nick)
                elif utils.is_hostmask(nick):
                    prepare_nicks.append(nick)
                else:
                    reason = " ".join(nicks[len(prepare_nicks):]).lstrip(": ")
                    break
            nicks = prepare_nicks
            for nick in nicks:
                if utils.is_hostmask(nick):
                    bmask = nick
                else:
                    bmask = utils.banmask(irc, nick)
                setmodes.append("+b {}".format(bmask))
                for affect in utils.ban_affects(irc, channel, bmask):
                    if affect not in affected and affect != irc.get_nick():
                        if irc.is_opped(affect, channel):
                            setmodes.append("-o {}".format(affect))
                        if irc.is_voiced(affect, channel):
                            setmodes.append("-v {}".format(affect))
                        affected.append(affect)
            if len(setmodes) == 0:
                return
            already_op = irc.is_opped(irc.get_nick(), channel)
            gotop = utils.getop(irc, channel)
            if gotop:
                for mode in utils.unsplit_modes(setmodes):
                    irc.mode(channel, mode)
                for nick in affected:
                    if reason:
                        irc.kick(channel, nick, reason)
                    else:
                        irc.kick(channel, nick)
                if not already_op:
                    irc.mode(channel, "-o {}".format(irc.get_nick()))
Example #26
0
    async def answer_query(self,
                           ctx,
                           query,
                           assumptions=[],
                           small=False,
                           debug=False):
        safe.sprint('wolfram|alpha :', ctx.author.name, ':', query)
        channel = ctx.channel
        author = ctx.author
        api = get_api(ctx.bot)

        # Filter out bad words
        enable_filter = False
        if not is_private(channel):
            enable_filter = await ctx.bot.settings.resolve('f-wolf-filter',
                                                           channel,
                                                           channel.guild,
                                                           default='nsfw'
                                                           not in channel.name)
        if enable_filter and wordfilter.is_bad(query):
            await ctx.send(FILTER_FAILURE)
            return

        # Perform the query
        try:
            async with ctx.typing():
                units = await ctx.bot.keystore.get(f'p-wolf-units:{author.id}')
                result = await api.request(query,
                                           assumptions,
                                           imperial=(units == 'imperial'),
                                           debug=debug)
        except (wolfapi.WolframError, wolfapi.WolframDidntSucceed):
            await ctx.send(ERROR_MESSAGE_NO_RESULTS)
        except asyncio.TimeoutError:
            print('W|A timeout:', query)
            await ctx.send(ERROR_MESSAGE_TIMEOUT.format(query))
        except aiohttp.ClientError as error:
            print('Wolf: HTTP processing error:', error.message)
            await ctx.send('The server threw an error. Try again in a moment.')
        except xml.parsers.expat.ExpatError as error:
            print('Wolf: XML processing error:', error)
            await ctx.send(
                'The server returned some malformed data. Try again in a moment.'
            )
        else:

            if len(result.sections) == 0:
                await ctx.send(ERROR_MESSAGE_NO_RESULTS)
                return

            is_dark = (
                await
                ctx.bot.keystore.get(f'p-tex-colour:{author.id}')) == 'dark'

            sections_reduced = result.sections if not small else list(
                cleanup_section_list(
                    itertools.chain(
                        [find_first(section_is_input, result.sections, None)],
                        list(filter(section_is_important, result.sections))
                        or [
                            find_first(section_is_not_input, result.sections,
                                       None)
                        ])))

            # Post images
            messages = []
            for img in process_images(sections_reduced, is_dark):
                messages.append(
                    await
                    ctx.send(file=image_to_discord_file(img, 'result.png')))
                await asyncio.sleep(1.05)

            # Assuptions are currently disabled because of a 'bug'.
            # I think it's that discord sends emoji reaction updates
            # on a different shard to the one that handles the channel
            # that the message is in, which means that the shard
            # receiving the notif doesn't know what to do with the info
            # it receives.
            embed, show_assuptions = await self.format_adm(
                ctx, result.assumptions, small)

            posted = await ctx.send(embed=embed)

            try:
                await posted.add_reaction(DELETE_EMOJI)
                if not small and show_assuptions:
                    await self.add_reaction_emoji(posted, result.assumptions)
            except discord.errors.NotFound:
                pass
            payload = {
                'assumptions': result.assumptions.to_json(),
                'query': query,
                'used': False,
                'blame': author.id,
                'channel id': posted.channel.id,
                'message id': posted.id,
                'image ids': [i.id for i in messages],
                'no change warning': False
            }
            await ctx.bot.keystore.set_json('wolfram',
                                            'message',
                                            str(posted.id),
                                            payload,
                                            expire=60 * 60 * 24)

            print('Done.')
Example #27
0
def send_picture(bot, update):
    bot.sendChatAction(chat_id=update.message.chat.id, action=telegram.ChatAction.TYPING)
    if security.is_authorized(update.message, 'webcam_allowed'):
        if utils.is_private(update.message):
            bot.sendPhoto(chat_id=update.message.chat.id, photo=get_picture(update.message.chat.id))
def send_welcome(bot, update):
    bot.sendChatAction(chat_id=update.message.chat.id, action=telegram.ChatAction.TYPING)
    if (utils.is_private(update.message)):
        bot.sendMessage(chat_id=update.message.chat_id, text='Benvenuto su ' + configuration.botname)
        bot.sendMessage(chat_id=update.message.chat_id, text='Non sono disponibili comandi.')