コード例 #1
0
    def for_image(self):
        if self.avatar_medium == 'unknown':
            profile_picture = Image.open(
                get_full_path('images', 'steam', 'default_image.png'))
        else:
            profile_picture = get_image(self.avatar_medium)

        name = limit_string_length(self.name, 10)
        hero = Image.open(
            get_full_path('images', 'heroes', f"{self.player.hero_id}.jpg"))
        rank = get_rank_picture(self.rank)
        prev_rank = get_rank_picture(self.previous_rank)
        hero_damage = parse_int_to_thousands_k(self.player.hero_damage)
        items = [
            ImageCell(get_item_picture(item_id))
            for item_id in self.player.get_item_ids()
        ]
        return [
            ImageCell(profile_picture),
            TextCell(name, font_size=22),
            ImageCell(hero),
            ImageCell(rank),
            ImageCell(prev_rank),
            TextCell(self.player.kills, font_size=22),
            TextCell(self.player.deaths, font_size=22),
            TextCell(self.player.assists, font_size=22),
            TextCell(hero_damage)
        ] + items
コード例 #2
0
ファイル: images.py プロジェクト: tumachine/discorddota
def get_rank_picture(rank: int):
    rank = int(rank)
    if rank < 10:
        return Image.open(
            get_full_path('images', 'ranks', 'not_calibrated.png'))
    if rank == 80:
        return Image.open(get_full_path('images', 'ranks', 'Top0.png'))
    rank_medal = rank // 10
    rank_stars = (rank % 10) // 2 + 1
    return Image.open(
        get_full_path('images', 'ranks', f'{rank_medal}-{rank_stars}.png'))
コード例 #3
0
    def generate_image(self):
        img = Image.open(get_full_path('images', 'templates', 'PlayersPregameSummary.png'))

        cell_lines = VerticalCellLines(
                        CellPositionGenerator(x_start=246, y_start=89,
                                              columns=[100, 100, 100, 100, 100, 100, 100, 100, 100, 100],
                                              column_spaces=[10, 10, 10, 10, 10, 20, 10, 10, 10, 10],
                                              rows=[90, 10, 60, 100, 100, 60, 60, 60, 60],
                                              row_spaces=[10, 0, 20, 20, 20, 20, 20, 0, 0])
        )

        img = cell_lines.draw([player.for_image() for player in self.players], img)
        img.save(get_full_path('images', 'tmp.png'))
コード例 #4
0
    async def get_match_summary(self, match_id: int, channel):
        self.bot.get_all_channels()
        match_summary_data = MatchSummaryData(match_id)
        match_summary_data.generate_image()
        text = match_summary_data.generate_text()

        await channel.send(text,
                           file=discord.File(get_full_path(
                               'images', 'tmp.png')))
コード例 #5
0
ファイル: text.py プロジェクト: tumachine/discorddota
def get_random_fact():
    text_path = get_full_path('texts', 'random_facts.csv')
    filesize = os.path.getsize(text_path)
    offset = randrange(filesize)

    with open(text_path, 'r') as f:
        f.seek(offset)
        f.readline()
        return f.readline()
コード例 #6
0
    def generate_image(self):
        img = Image.open(
            get_full_path('images', 'templates', 'PostgameSummaryTest.png'))

        side_won_color = (0, 200,
                          0) if self.match_details.radiant_win else (200, 0, 0)
        side_won_cell = TextCell(self.match_details.side_won_text,
                                 font_size=36,
                                 font_color=side_won_color)
        side_won_cell.draw(img, CellPosition(360, 120, 20, 160))

        radiant_score_cell = TextCell(self.match_details.radiant_score,
                                      font_size=45,
                                      font_color=(0, 200, 0))
        radiant_score_cell.draw(img, CellPosition(140, 80, 120, 380))

        dire_score_cell = TextCell(self.match_details.dire_score,
                                   font_size=45,
                                   font_color=(200, 0, 0))
        dire_score_cell.draw(img, CellPosition(140, 80, 120, 650))

        duration_cell = TextCell(self.match_details.duration_text,
                                 font_size=40)
        duration_cell.draw(img, CellPosition(180, 100, 110, 500))

        # no need to generate it each time, would be enough to save it in memory or disk
        cell_lines = HorizontalCellLines(
            CellPositionGenerator(
                x_start=400,
                y_start=140,
                columns=[
                    100, 220, 100, 100, 100, 40, 40, 40, 100, 100, 100, 100,
                    100, 100, 100
                ],
                column_spaces=[
                    10, 20, 20, 20, 20, 20, 20, 20, 20, 20, 0, 0, 0, 0, 0, 0
                ],
                rows=[60, 60, 60, 60, 60, 60, 60, 60, 60, 60],
                row_spaces=[10, 20, 20, 20, 20, 170, 20, 20, 20, 20]))

        players = [player.for_image() for player in self.players]
        cell_lines.draw(players, img)
        img.save(get_full_path('images', 'tmp.png'))
コード例 #7
0
    def generate_image(self):
        img = Image.open(
            get_full_path('images', 'templates', 'PlayerHeroStatsTest.png'))

        # title_cell = TextCell(20, 20, 1610, 60)
        player_summary = PlayerSummaries(
            api.get_player_summaries(self.steam_id))
        title_cell = TextCell(
            f"Hero summary for {player_summary.players[0].personaname}",
            font_size=24)
        title_cell.draw(img, CellPosition(1610, 60, 20, 20))

        hero_image = Image.open(
            get_full_path('images', 'heroes', f"{self.hero_id}.jpg"))
        hero_cell = ImageCell(hero_image)
        hero_cell.draw(img, CellPosition(300, 280, 20, 100))

        hero_name_cell = TextCell(self.hero_name, font_size=22)
        hero_name_cell.draw(img, CellPosition(300, 100, 20, 400))

        # no need to generate it each time, would be enough to save it in memory or disk
        cell_lines = HorizontalCellLines(
            CellPositionGenerator(
                x_start=340,
                y_start=140,
                columns=[
                    100, 100, 100, 40, 40, 40, 100, 100, 100, 100, 100, 100,
                    100
                ],
                column_spaces=[15, 25, 20, 20, 20, 20, 20, 20, 0, 0, 0, 0, 0],
                rows=[60, 60, 60, 60, 60],
                row_spaces=[10, 20, 20, 20, 20]))

        players = [
            match.draw_for_player_hero_stats(self.steam_id)
            for match in self.matches
        ]
        cell_lines.draw(players, img)
        img.save(get_full_path('images', 'tmp.png'))
コード例 #8
0
    async def send_player_info(self, server_log: ServerLog):
        await self.bot.wait_until_ready()
        start_time = time.time()
        players = await api.build_async_request(api.get_stratz_player, server_log.players_lobby)
        players_hero_performance = await api.build_async_request(api.get_stratz_player_hero_performance, server_log.players_lobby)
        players_party_color = await assign_players_party_color(server_log.players_lobby, 5, 2)
        print(f"30 api calls in {time.time() - start_time}")

        p = PlayersPregameSummaryData(server_log, players, players_hero_performance, players_party_color)
        text = p.generate_text()
        text_channel_id = config.get_value('text_channel')
        text_channel = self.bot.get_channel(int(text_channel_id))
        await p.play_voice_highest_rank_player(self.bot)
        p.generate_image()
        await text_channel.send(file=discord.File(get_full_path('images', 'tmp.png')))
コード例 #9
0
class BaseVoice(metaclass=ABCMeta):
    default_voice_path = get_full_path('sounds', 'tmp.wav')
    voice = tts.sapi.Sapi()
    voice.set_voice(config.get_value('voice'))

    @staticmethod
    def stop(bot):
        pass

    @staticmethod
    def play(bot, path):
        pass

    @staticmethod
    def play_text(bot, text):
        pass
コード例 #10
0
    def for_image(self):
        # hero_performances = StratzPlayerHeroPerformances(api.get_stratz_player_hero_performance(self.stratz_player.steam_id))
        hero_ids = [hero_performance.hero_id for hero_performance in self.hero_performance.sort_by_best(3)]

        heroes = []
        for hero_id in hero_ids:
            heroes.append(ImageCell(Image.open(get_full_path('images', 'heroes', f"{hero_id}.jpg"))))

        return [
            ImageCell(get_image(self.stratz_player.avatar_full)),
            ColorCell(self.color),
            TextCell(self.name),
            ImageCell(get_rank_picture(self.rank)),
            ImageCell(get_rank_picture(self.previous_rank)),
            TextCell(f"{self.stratz_player.match_count}\n{self.stratz_player.winrate}%"),
            heroes[0], heroes[1], heroes[2]
        ]
コード例 #11
0
def setup_log():
    # Load logging configuration
    logger = logging.getLogger('sLogger')
    filename = config.get_log_path().replace("\\", "\\\\")
    if os.path.exists(filename):
        logger.info("log file initialized successfully")
    else:
        os.mkdir(get_full_path('log'))
    logging.config.fileConfig(Configuration.get_config_path(),
                              defaults={'logfilename': filename})

    # Create the logger
    # sLogger: The name of a logger defined in the config file

    logger.info("-----------------------------------")
    logger.info("Log system successfully initialised")
    logger.info("-----------------------------------")
    return logger
コード例 #12
0
    def draw(self, image_on, cell_position: CellPosition):
        text = str(self.text)
        if 'centered' not in self.rules:
            centered = True
        else:
            centered = self.rules['centered']

        if 'font_size' not in self.rules:
            font_size = 16
        else:
            font_size = self.rules['font_size']

        if 'font_color' not in self.rules:
            font_color = (255, 255, 255)
        else:
            font_color = self.rules['font_color']

        if 'font_opacity' not in self.rules:
            font_opacity = 256
        else:
            font_opacity = self.rules['font_opacity']

        if 'font_name' not in self.rules:
            font_name = 'Roboto-Medium.ttf'
        else:
            font_name = self.rules['font_name']

        fnt = ImageFont.truetype(get_full_path('fonts', font_name), font_size)
        draw = ImageDraw.Draw(image_on)
        w, h = draw.textsize(text, font=fnt)
        if centered:
            draw.text(cell_position.get_xy_to_center_element(w, h),
                      text,
                      font=fnt,
                      fill=font_color + (font_opacity, ))
        else:
            draw.text((cell_position.x, cell_position.y),
                      text,
                      font=fnt,
                      fill=font_color + (font_opacity, ))
コード例 #13
0
    async def hero(self, ctx, hero_name: str):
        user = ManageUser.load(ctx.message.author)
        if not user:
            await ctx.send('Not registered, to register type !connect steam_id'
                           )
            return

        hero_id = get_by_id.get_hero_id_by_name(hero_name)
        if hero_id == -1:
            await ctx.send('No hero with this name')
            return

        match_hero_history = MatchHistory(
            api.get_match_history(user.steam_id, hero_id=hero_id))
        if match_hero_history.num_results < 5:
            await ctx.send(
                'You have less than 5 games played on this hero, I cannot currently provide stats for that'
            )
            return

        matches = []
        match_ids = []
        for count, match in enumerate(match_hero_history.matches):
            if count == 5:
                break
            matches.append(MatchDetails(api.get_match_details(match.match_id)))
            # match_ids.append(match.match_id)
        # matches = asyncio.run_coroutine_threadsafe(api.build_async_request(api.get_match_details, match_ids, get_url=None), self.bot.loop).result()
        # des_matches = [MatchDetails(match) for match in matches]
        # matches.append(MatchDetails(api.get_match_details(match.match_id)))

        PlayerHeroStatsData(matches, hero_id, hero_name,
                            user.steam_id).generate_image()
        # PlayerHeroStatsData(matches, hero_id, hero_name, user.steam_id).generate_image()
        await ctx.channel.send(
            file=discord.File(get_full_path('images', 'tmp.png')))
コード例 #14
0
from bs4 import BeautifulSoup
import requests
from utils.util import get_full_path

source = requests.get(
    'https://sguru.org/steam-profile-pictures-184px/').content

soup = BeautifulSoup(source, 'html.parser')

img_links = []


def fill_image_links():
    for i in range(136, 146):
        for image_list in soup.find_all(attrs={'id': f'gallery-{i}'}):
            for image_link in image_list.find_all(
                    attrs={'class': 'herald-popup'}):
                img_links.append(image_link['href'])


fill_image_links()

count = 0
for image in img_links:
    r = requests.get(image)
    with open(get_full_path('images', 'steam', f'{count}.jpg'), 'wb') as f:
        f.write(r.content)
    count += 1

print('a')
コード例 #15
0
 def get_random_rune_path():
     path = get_full_path('sounds', 'roons')
     sounds = os.listdir(path)
     random_sound = sounds[random.randint(0, len(sounds) - 1)]
     random_sound_path = os.path.join(path, random_sound)
     return random_sound_path
コード例 #16
0
ファイル: parse.py プロジェクト: tumachine/discorddota
def load_json_file(file_name):
    return get_full_path('dota2api', 'ref', file_name)
コード例 #17
0
ファイル: index.py プロジェクト: tumachine/discorddota
import os

from discord.ext import commands

from dota2api import Initialise
from utils.config_manage import ConfigManage
from utils.util import get_full_path

# DAVID
# ZIRA
# IRINA


config = ConfigManage(get_full_path('config_test.json'))
api = Initialise(config.get_value('api_key'))
bot = commands.Bot(command_prefix=config.get_value('prefix'))


if __name__ == "__main__":
    for file in os.listdir("cogs"):
        if file.endswith('.py'):
            name = file[:-3]
            bot.load_extension(f'cogs.{name}')

    bot.run(config.get_value('token'))

# channel = self.bot.get_channel(532657285923864608)
# guild = self.bot.get_guild(532657285923864606)
# test_channel = 53265728592386460811111
# main_channel = 199929173521727501
コード例 #18
0
    for item in json_dict:
        new_dict[item['id']] = item
        dict.pop(new_dict[item['id']], 'id')
    save_dict_to_file(new_dict, path_to)


def convert_json_files(folder_to_load, folder_to_save, file_json_names):
    for file_name in file_json_names:
        json_name = file_name + '.json'
        path_from = os.path.join(folder_to_load, json_name)
        path_to = os.path.join(folder_to_save, json_name)

        json_dict = load_json_file(path_from)
        if not isinstance(json_dict, list):
            json_dict = json_dict[file_name]

        convert_to_id(json_dict, path_to)


# folder_to_load_from = get_full_path('dota2api', 'ref', 'outdated')
# folder_to_save = get_full_path('dota2api', 'ref')
#
# file_json_names = ['abilities', 'leaver', 'lobbies', 'modes', 'regions']

folder_to_load_from = get_full_path('dota2api', 'ref', 'test')
folder_to_save = get_full_path('dota2api', 'ref')

file_json_names = ['region', 'cluster']
convert_json_files(folder_to_load_from, folder_to_save, file_json_names)
コード例 #19
0
from peewee import *
from utils.util import get_full_path

db = SqliteDatabase(get_full_path('DB', 'discord.db'))


class ModelClass(Model):
    class Meta:
        database = db


class User(ModelClass):
    discord_id = CharField()
    steam_id = CharField()
    last_match = CharField()


db.connect()
db.create_tables([User])
コード例 #20
0
ファイル: images.py プロジェクト: tumachine/discorddota
def get_item_picture(item_id: int):
    if item_id == 0:
        return None
        # return Image.open(get_full_path('images', 'items', f"279.jpg"))
    return Image.open(get_full_path('images', 'items', f"{item_id}.jpg"))