Exemplo 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()         
Exemplo n.º 2
0
 def check_config(self):
     cfg_path = "configs/{}/dlc.json".format(self.selected_game)
     if dataIO.is_valid_json(cfg_path) is False:
         self.owns = False
         QMessageBox.warning(self, "Warning", "'dlc.json' from '{}' have errors or not found, "
                                              "functionality has been limited".format(self.selected_game))
     else:
         self.owns = {}
         self.dlc = dataIO.load_json(cfg_path)
Exemplo n.º 3
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)
Exemplo n.º 4
0
 async def notice(self, ctx, *, message=None):
     author = ctx.author
     if message == None:
         return await ctx.send(f'{author.mention}, 메시지를 적어주세요!')
     data = dataIO.load_json('channel.json')
     if data.get('channel') == None:
         return await ctx.send(f'{author.mention}, 공지 데이터가 없습니다!')
     em = discord.Embed(colour=0xFFC0CB)  #색깔은 HEX코드입니다!
     em.add_field(name=f'{ctx.bot.user.name} 공지', value=message)
     em.set_footer(text=f'공지 작성자: {author} - 인증됨',
                   icon_url=author.avatar_url)
     a = data.get('channel')
     if a == None:
         return await ctx.send('공지 채널이 설정되지 않아 취소되었습니다!')
     for id in a:
         await self.bot.get_channel(int(id)).send(embed=em)
     return await ctx.send('모든 채널에 전송을 완료했습니다!')
Exemplo n.º 5
0
def displayResult(matchOdotaJson):
    chatLog = matchOdotaJson['chat']
    players = {}
    for player in matchOdotaJson['players']:
        players[player['player_slot']] = {'account_id': player.get('account_id', None),
                                          'personaname': player.get('personaname', None),
                                          'hero_id': player.get('hero_id', None)}

    introTemplate = '####	\n#####	 Hover to view [chat log](https://www.opendota.com/matches/{matchid}/chat)\n######	\n\n' \
                    'This chat log was provided by [**OpenDota**](https://www.opendota.com/matches/{matchid}/chat)\'s free replay parsing.\n\n'
    chatHeader = 'Player | Time | Message\n' \
                 ':-- | :-- | :--\n'
    chatLineTemplate = '[](/hero-{heroName}) {playerName} | {time} | {message}\n'

    intro = introTemplate.format(matchid=matchOdotaJson['match_id'])

    print(chatLog)
    chatResult = chatHeader
    for i in range(0, len(chatLog)):
        time = timeconverter.durationTimeConverter(chatLog[i]['time'])
        heroName = heroDictionary[players[chatLog[i]['player_slot']]['hero_id']]
        if players[chatLog[i]['player_slot']]['personaname'] is not None:
            playerName = '%.9s' %players[chatLog[i]['player_slot']]['personaname']
        else:
            playerName = ''

        if chatLog[i]['type'] == 'chat':
            message = chatLog[i]['key']
        elif chatLog[i]['type'] == 'chatwheel':
            chatwheelFile = 'data/chatwheel.json'
            chatwheel = dataIO.load_json(chatwheelFile)
            message = '▶ ' + chatwheel[chatLog[i]['key']]


        chatResult += chatLineTemplate.format(heroName=heroName, playerName=playerName, time=time, message = message)

    return (intro + chatResult + '\n---\n\n')
Exemplo n.º 6
0
import praw
import secret
import re
import template as temp
from dataIO import dataIO

if dataIO.is_valid_json("settings.json"):
    settings = dataIO.load_json("settings.json")
    print("loaded json")
else:
    settings = {"maeve_cash": 00.00}
    print("couldn't load json")

footer = temp.footer  # this is for any announcements, etc

# scoping smh my head

pattern = re.compile(
    r"(?i)maeve,? ?not,? ?(?:\"|\'|) ?(?:me?ai?y?u?ve|mayve?) ?(?:\"|\'|)")
misspell = re.compile(r"(?i)(?:me?ai?y?u?ve|mayve?)")


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
Exemplo n.º 7
0
    def __init__(self, selected_game, owns_list, parent=None):
        # Setup UI
        QDialog.__init__(self, parent, flags=Qt.Window)
        Ui_SecondWindow.__init__(self)
        self.ui = Ui_SecondWindow()
        self.ui.setupUi(self)

        self.owns = owns_list  # From main window

        # Checking files
        cfg_path = "configs/{}".format(selected_game)
        dealers_path = "{}/dealers.json".format(cfg_path)
        agencies_path = "{}/agencies.json".format(cfg_path)
        if dataIO.is_valid_json(dealers_path) is False:
            self.dealers = False
            self.ui.dealer_edit.setEnabled(False)
            self.ui.dealer_add.setEnabled(False)
            self.ui.dealer_add_all.setEnabled(False)
            QMessageBox.warning(
                self, "Warning",
                "'dealers.json' from '{}' have errors or not found.\n"
                "Dealers editing has been disabled".format(selected_game))
        else:
            self.dealers = []
            self.dealers_file = dataIO.load_json(dealers_path)

        if dataIO.is_valid_json(agencies_path) is False:
            self.agencies = False
            self.ui.agency_edit.setEnabled(False)
            self.ui.agency_add.setEnabled(False)
            self.ui.agency_add_all.setEnabled(False)
            QMessageBox.warning(
                self, "Warning",
                "'agencies.json' from '{}' have errors or not found.\n"
                "Agencies editing has been disabled".format(selected_game))
        else:
            self.agencies = []
            self.agencies_file = dataIO.load_json(agencies_path)

        self.ui.garage_size.addItem("Small")
        self.ui.garage_size.addItem("Medium")
        self.ui.garage_size.addItem("Big")

        # Dealers and agencies properties
        self.da_array = {
            self.ui.dealer_add: [
                self.ui.dealer_edit, "unlocked_dealers:", "Dealership",
                self.dealers, self.check_dealers
            ],
            self.ui.agency_add: [
                self.ui.agency_edit, "unlocked_recruitments:",
                "Recruitment agency", self.agencies, self.check_agencies
            ],
        }

        # Connecting buttons
        self.ui.garages_analyze.clicked.connect(self.check_garages)
        self.ui.garage_add.clicked.connect(self.add_garage)
        self.ui.garage_add_all.clicked.connect(self.add_all_garages)
        self.ui.headquarter_change.clicked.connect(self.change_headquarter)
        self.ui.city_add.clicked.connect(self.add_city)
        self.ui.city_add_all.clicked.connect(self.add_all_cities)
        self.ui.dealer_add.clicked.connect(self.da_clicked)
        self.ui.dealer_add_all.clicked.connect(self.add_all_dealers)
        self.ui.agency_add.clicked.connect(self.da_clicked)
        self.ui.agency_add_all.clicked.connect(self.add_all_agencies)

        if self.owns:
            self.fill_list(self.dealers, self.dealers_file)
            self.fill_list(self.agencies, self.agencies_file)
        # Checking save-file
        self.check_cities()
        self.check_dealers()
        self.check_agencies()
Exemplo 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))
Exemplo 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)