Ejemplo n.º 1
0
async def on_message(message):
    # 메세지 채널을 메세지 채널로 변수 설정
    messageauthorchannel = message.channel
    # 메세지 유저를 유저로 변수 설정
    user = message.author
    # s는 설정 프리픽스 와 설정 명령어
    s = set.first + set.second
    if s in message.content:
        # 만약 유저가 따노슈(봇 소유주)가 될 경우
        if message.author.id in owner:
            # dataIO를 이용해서 channel.json 파일 로드 
            #  메세지 유저를 author로 변경 
            author = message.author
            # 메세지 보내는 서버를 보낸 서버로 지정
            authorserver=message.author.server
            # 보낼 채널 channel id 가져오기 
            channels_to_send = dataIO.load_json('channel.json')['channel']
            for channels_to_send in channels_to_send:
                if message is None:
                    pass
                else:
                    channel = bot.get_channel(channels_to_send)
                    em = discord.Embed(colour=0x80ff80)
                    em.add_field(name='공지', value=message.content[3:])
                    em.set_footer(text='공지 작성자: ' + author.name + ' - 인증됨',icon_url=author.avatar_url)
                    await bot.send_message(channel, embed=em)
        # 아닐 경우
        else:
            # 관리자 아니라고 보냄
            await bot.send_message(messageauthorchannel, '{}, 당신은 관리자가 아닙니다!'.format(user.mention))
         #만약 설정 프리픽스랑 설정 공지가 메세지 이면   
    elif set.first + set.notice in message.content:
        # 디스코드 채널 맨션을 채널로 변수 설정
        channel = message.content[8:26]
        # setting.json에 로드 하는 데 변수 설정
        notice = dataIO.load_json('channel.json')
        # setting.json에 채널 id를 등록
        notice['channel'].append(channel)
        # setting.json 저장
        dataIO.save_json('channel.json', notice)            
    elif set.first + set.remove in message.content:
        # 디스코드 채널 맨션을 채널로 변수 설정
        channel = message.content[8:26]
        # setting.json에 로드 하는 데 변수 설정
        notice = dataIO.load_json('channel.json')
        # setting.json에 채널 id를 삭제
        notice['channel'].remove(channel)
        # setting.json 저장
        dataIO.save_json('channel.json', notice)            
    elif set.first + 'shutdown' in message.content:
        await bot.logout()         
Ejemplo n.º 2
0
    async def 공지등록(self, ctx, channel: discord.TextChannel = None):
        author = ctx.author
        if not channel:
            return await ctx.send(f'{author.mention}, 채널을 멘션 해주세요!')
        data = dataIO.load_json('channel.json')
        em = discord.Embed(colour=0x42FF33,
                           title='채널 설정',
                           timestamp=datetime.datetime.utcnow())
        em.add_field(name='정말 진행하시겠습니까?',
                     value=f'정말 {channel.mention} 채널을 공지 채널로 하시겠습니까?')
        asdf = ['⭕', '❌']
        msg = await ctx.send(embed=em)
        for a in asdf:
            await msg.add_reaction(a)

        def check(reaction, user):
            if user == ctx.author and str(reaction.emoji) in asdf:
                return True

        try:
            reaction, user = await self.bot.wait_for('reaction_add',
                                                     timeout=30.0,
                                                     check=check)
        except asyncio.TimeoutError:
            return await msg.edit(content='> 정상적으로 취소되었습니다!')
        if True:
            em2 = discord.Embed(colour=0x42FF33,
                                title='채널 설정',
                                timestamp=datetime.datetime.utcnow())
            if reaction.emoji == '⭕':
                if data.get('channel') == None:
                    data['channel'] = []
                if data.get('server') == None:
                    data['server'] = []
                if ctx.guild.id in data.get('server'):
                    await msg.delete()
                    return await ctx.send(
                        f'{author.mention}, 이 서버는 이미 공지 채널이 등록 되있습니다! `{ctx.prefix}공지삭제` 명령어로 채널을 삭제하세요!'
                    )
                data['channel'].append(int(channel.id))
                data['server'].append(int(ctx.guild.id))
                dataIO.save_json('channel.json', data)
                em2.add_field(name='성공!',
                              value=f'공지 채널을 {channel.mention}으로 설정하였습니다!')
                return await msg.edit(content=author.mention, embed=em2)
            if reaction.emoji == '❌':
                em2.add_field(name='실패!', value='취소되었습니다.')
                return await msg.edit(content=author.mention, embed=em2)
            else:
                em2.add_field(name='실패!', value='다른 이모지를 추가하셔서 취소되었습니다.')
                return await msg.edit(content=author.mention, embed=em2)
Ejemplo n.º 3
0
def update_configs(is_save, cfg_list):
    if is_save in (0, 1):
        for cfg in cfg_list:
            check_path(cfg)
            response_status, response = get_response_result(github_link + cfg)
            if response_status:
                remote_cfg = literal_eval(response.text)
                if dataIO.is_valid_json(cfg) or os.path.exists(cfg):
                    dataIO.save_json(cfg, remote_cfg)
    if is_save in (1, 3):
        text = str({
            "answer_updates": is_save == 3,
            "update_on_start": is_save == 1
        })
        with open(update_config_name, "w") as f:
            f.write(text)
Ejemplo n.º 4
0
 def save_file(self):
     if self.file_path != "":
         data = literal_eval(self.ui.textEdit.toPlainText())
         ret = dataIO.save_json(self.file_path, data)
         if ret:
             self.ui.textEdit.document().setModified(False)
             self.setWindowModified(False)
         return ret
Ejemplo n.º 5
0
def lobot(r, sub):
    nothings = 0
    monies = settings["maeve_cash"]
    last_run = settings.get("maeve_last_run")
    print("now at ${}, last run was {} \n \n \n".format(monies, last_run))
    for comment in r.subreddit(sub).comments(limit=9999):
        # somehow comment.author.name isn't working
        if str(comment.author) == "REEvie_bot":
            continue  # skip this iteration and move on to next comment

        # skip comments created before the most recent comment from the last run (prevents from replying twice to the same comment)
        if last_run:  # can be None if the settings file didn't exist or got corrupted
            if comment.created_utc <= last_run:
                print(str(comment) + " was already replied to, breaking loop.")
                break

        if pattern.search(comment.body
                          ):  # search for people correctiong others' spelling
            comment.reply("Thank you! You've saved someone a quarter.")
            print("thanked " + str(comment))
        elif misspell.search(comment.body):  # search for a misspell
            monies += 0.25
            comment.reply(
                "If I had a quarter for every time someone misspelled Maeve, I would have $"
                + (str(monies) if str(monies)[-3] == "." else str(monies) +
                   "0") + "." + footer)
            print("fined " + str(comment))
        else:
            nothings += 1

    newest_comment = next(
        r.subreddit(sub).comments(limit=1))  # get the most recent comment
    settings[
        "maeve_last_run"] = newest_comment.created_utc  # store the creation time of it as Unix timestamp
    # print(settings)
    settings[
        "maeve_cash"] = monies  # save current amount of hypothetical quarters
    dataIO.save_json("settings.json", settings)  # save to file
    print("oof: {} comments with nothing \n \n \n".format(nothings))
Ejemplo n.º 6
0
 def save_as(self):
     file_path, file_name = QFileDialog.getSaveFileName(
         parent=self,
         caption=self.tr("Select place to save file"),
         filter=self.tr("*.json"))
     file_data = literal_eval(self.ui.textEdit.toPlainText())
     ret = dataIO.save_json(file_path, file_data)
     if ret:
         self.file_path = file_path
         self.setWindowTitle(
             self.tr("[*]{} - {}".format(file_path, self.win_title)))
         self.ui.textEdit.document().setModified(False)
         self.setWindowModified(False)
Ejemplo n.º 7
0
def loboto(r, sub):
    nothings = 0  # for debug
    tags = 0
    last_run = settings.get("reevie_last_run")
    for comment in r.subreddit(sub).comments(
            limit=7999):  # change to 9999 later

        if str(comment.author) == "REEvie_bot":  # prevents self reply
            continue  # skip this iteration and move on to next comment

        # skip comments created before the most recent comment from the last run (prevents from replying twice to the same comment)
        if last_run:  # can be None if the settings file didn't exist or got corrupted
            if comment.created_utc <= last_run:
                print(
                    str(comment) +
                    " was already replied to, breaking loop. \n")
                break

        # print("evaluating "+str(comment))

        if bool(tagcheck.search(comment.body)
                ) == False:  # only check comments that mention the bot
            nothings += 1
            continue

        reply = ""  # for each comment, start with an empty reply

        comment_words = re.compile(r"\b").split(
            comment.body.upper())  # get a list of words used
        for word in comment_words:  # for each word in a comment
            match = pattern.search(
                word)  # try to match it with the filter pattern
            if match:  # if there is a match
                command = match.group(0)  # extract what the command was
                voiceline = commands.get(
                    command
                )  # use it to look up the tuple containing the command's text (T) and voice line link (V)
                if command is None:
                    print("couldn't find vgs key")
                    continue  # if VGS key can't be found, move on to next word
                reply += ">{} (Evie): [[{}] {}]({}) \n \n".format(
                    comment.author.name, command, *voiceline
                )  # * unpacks tuple and puts all its elements into format()
        if len(
                reply
        ) > 0:  # check if the length of the reply is more than 0 - if yes, that means we have something to reply with
            reply += "\n\n ^^^^^^^^^^^^^i'm ^^^^^^^^^^^^^a ^^^^^^^^^^^^^bot! ^^^^^^^^^^^^^check [^^^^^^^^^^^^^this ^^^^^^^^^^^^^post](https://www.reddit.com/user/yubbber/comments/a8q81v/about_ureevie_bot/) ^^^^^^^^^^^^^for ^^^^^^^^^^^^^info."
            comment.reply(reply)  # reply! \o/\o/ (above line is reply footer)
            print("replied to " + comment.body)
        else:  # if the comment only has the tag but not vgs, check parent
            if hasattr(comment.parent(), 'body'):
                parentbody = comment.parent(
                ).body  # if the parent is a comment get its body
            elif hasattr(comment.parent(), 'selftext'):
                parentbody = comment.parent(
                ).selftext  # if it's a post get its content (selftext)
            else:
                print(str(comment) + " parent invalid.")

            if str(comment.parent().author) != "REEvie_bot":
                comment_words = re.compile(r"\b").split(
                    parentbody.upper())  # split the parent body
                for word in comment_words:
                    match = pattern.search(
                        word)  # try to match it with the filter pattern
                    if match:  # if we were successful
                        # for i in range(pattern.groups): # uncomment this line for comparing pattern to entire comment body
                        command = match.group(
                            0
                        )  # extract what the command was - if above line used, replace 0 with i
                        voiceline = commands.get(
                            command
                        )  # use it to look up the tuple containing the command's text (T) and voice line link (V)
                        if command is None:
                            print("couldn't find vgs key")
                            continue  # if VGS key can't be found, move on to next word
                        reply += ">{} (Evie): [[{}] {}]({}) \n \n".format(
                            comment.parent().author.name, command, *voiceline
                        )  # * unpacks tuple and puts all its elements into format()
                if len(
                        reply
                ) > 0:  # check if the length of the reply is more than 0 - if yes, that means we have something to reply with
                    reply += "\n\n ^^^^^^^^^^^^^i'm ^^^^^^^^^^^^^a ^^^^^^^^^^^^^bot! ^^^^^^^^^^^^^check [^^^^^^^^^^^^^this ^^^^^^^^^^^^^post](https://www.reddit.com/user/yubbber/comments/a8q81v/about_ureevie_bot/) ^^^^^^^^^^^^^for ^^^^^^^^^^^^^info. \n \n" + footer
                    comment.reply(reply)  # reply! \o/\o/
                    print("tag replied to " + parentbody)
                    tags += 1
                else:
                    nothings += 1
            # print("nothing in "+str(comment)+reply)

    # print(settings)
    newest_comment = next(
        r.subreddit(sub).comments(limit=1))  # get the most recent comment
    settings[
        "reevie_last_run"] = newest_comment.created_utc  # store the creation time of it as Unix timestamp
    dataIO.save_json("settings.json", settings)  # save to file
    print("oof: {} comments with nothing \n \n \n".format(nothings))
Ejemplo n.º 8
0
def main(r, qui, sub, filterfun, footer=defaultfooter, jsonbackup={}, *misc):
    '''
    template function for comment checking and looping.

    iterates through last 7999 comments of sub. if their author is not reevie_bot and was made after last run, call fun and add returned value to reply, then reply if reply is not empty

    Args

    r - val from login()
    qui - str (reevie, maeve, grohk)
    sub - which subreddit to run the bot in
    fun - function for bot logic. must return string, which will be added to reply (no reply if end up empty)

    Kwargs

    footer - text to put at the bottom of the comment. value of template.defaultfooter by default
    jsonbackup - dict to replace json when it's unloadable. {} by default.
    misc - additional args.
    '''

    import praw
    from dataIO import dataIO

    # defaults = 'praw dataIO'.split(" ") # the prereqs we need for every bot
    # rd = {} # requisite dictionary
    # for i in defaults:
    #     rd[i] = importlib.import_module(i) # import every module we need
    # # if using reqdict replace module names with rd['modulename']

    login(qui)  # log us in

    if dataIO.is_valid_json(
            "settings.json"):  # check file integrity then load it
        main.settings = dataIO.load_json("settings.json")
        print(main.settings)
    else:
        main.settings = jsonbackup  # use our backup dict if our file is f****d
        print("couldn't load json")

    # init
    nothings = 0
    reply = ''

    # main
    main.last_run = main.settings.get("{}_last_run".format(qui))
    for comment in r.subreddit(sub).comments(
            limit=7999):  # change to 9999 later

        reply = ''

        if str(comment.author) == "REEvie_bot":  # prevents self reply
            continue  # skip this iteration and move on to next comment

        # skip comments created before the most recent comment from the last run (prevents from replying twice to the same comment)
        if main.last_run:  # can be None if the settings file didn't exist or got corrupted
            if comment.created_utc <= main.last_run:
                print(
                    str(comment) +
                    " was already replied to, breaking loop. \n")
                break

        reply = filterfun(comment, misc)

        if reply:  # reply only if str is nonempty
            comment.reply(reply + footer)
        else:
            nothings += 1

    newest_comment = next(
        r.subreddit(sub).comments(limit=1))  # get the most recent comment
    main.settings["{}_last_run".format(
        qui
    )] = newest_comment.created_utc  # store the creation time of it as Unix timestamp
    dataIO.save_json("settings.json", main.settings)  # save to file
    print("oof: {} comments with nothing \n \n \n".format(nothings))
Ejemplo n.º 9
0
import sys
sys.path.insert(0, 'utils')

from dataIO import dataIO


test_list = []
for i in range(10):
    test_d = {'Hello':i}
    test_list.append(test_d)

if not dataIO.is_valid_json("../data/test.json"):
    print("Creating empty {}...".format("test.json"))
    dataIO.save_json("../data/test.json", [])

dataIO.save_json("../data/test.json", test_list)

json_test = dataIO.load_json("../data/test.json")

print (json_test)