Skip to content

Commit

Permalink
Merge pull request #81 from tetsuya-ki/develop
Browse files Browse the repository at this point in the history
Developから取り込み
  • Loading branch information
tetsuya-ki authored Jan 1, 2024
2 parents cfddc26 + ce5010b commit 0ba38a4
Show file tree
Hide file tree
Showing 10 changed files with 501 additions and 331 deletions.
3 changes: 2 additions & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,8 @@ WORDWOLF_JSON_URL=\
NGWORD_GAME_JSON_URL=\
ENABLE_SLASH_COMMAND_GUILD_ID=\
APPLICATION_ID=\
USE_IF_AVAILABLE_FILE=False
USE_IF_AVAILABLE_FILE=False\
USE_TWITTER_EXPANDED=True

WORKDIR $dir
RUN poetry update && poetry install
Expand Down
1 change: 1 addition & 0 deletions assistantbot.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ async def main():
intents.typing = False
intents.presences = False
intents.message_content = True # このBotでは必須(特権インテントの設定が必要)
LOG.info(settings.APPLICATION_ID)

bot = AssistantBot(
command_prefix = '/'
Expand Down
6 changes: 4 additions & 2 deletions cogs/gamecog.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ async def wordWolf_setting(self):
# ファイルを読み込み、ワードウルフ用のデータを作成
read_json = ReadJson()
read_json.readJson(wordWolf_filepath)
LOG.info(read_json)
self.wordWolfJson = read_json

async def ngWordGame_setting(self):
Expand All @@ -72,15 +73,16 @@ async def ngWordGame_setting(self):
# ファイルを読み込み、NGワードゲーム用のデータを作成
read_json = ReadJson()
read_json.readJson(ngWordGame_filepath)
LOG.info(read_json)
self.ngWordGameJson = read_json

async def json_setting(self, json_url=None, file_name='no_name.json'):
json_path = join(dirname(__file__), 'modules' + os.sep + 'files' + os.sep + 'temp' + os.sep + file_name)
# URLが設定されている場合はそちらを使用
if json_url:
file_path = await self.savefile.download_file(json_url, json_path)
LOG.info(f'JSONのURLが登録されているため、JSONを保存しました。\n{file_path}')
return file_path
LOG.info(f'JSONのURLが登録されているため、JSONを保存しました。\npath:{json_path}\nfile_path:{file_path}')
return json_path

# ワードウルフ機能
@app_commands.command(
Expand Down
3 changes: 2 additions & 1 deletion cogs/modules/files/.env-docker.sample
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,5 @@ WORDWOLF_JSON_URL=wordwolf_json_url
NGWORD_GAME_JSON_URL=ngword_game_json_url
APPLICATION_ID="99999999" # YOUR_DISCORD_BOT_APPLICATION_ID
ENABLE_SLASH_COMMAND_GUILD_ID="99999999"
USE_IF_AVAILABLE_FILE=False
USE_IF_AVAILABLE_FILE=False
USE_TWITTER_EXPANDED=True
3 changes: 2 additions & 1 deletion cogs/modules/files/.env.sample
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,5 @@ WORDWOLF_JSON_URL = "wordwolf_json_url"
NGWORD_GAME_JSON_URL = "ngword_game_json_url"
APPLICATION_ID = "99999999" # YOUR_DISCORD_BOT_APPLICATION_ID
ENABLE_SLASH_COMMAND_GUILD_ID = "99999999"
USE_IF_AVAILABLE_FILE = False
USE_IF_AVAILABLE_FILE = False
USE_TWITTER_EXPANDED = True
3 changes: 2 additions & 1 deletion cogs/modules/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,4 +62,5 @@ def split_guild_env(str):
NGWORD_GAME_JSON_URL = os.environ.get('NGWORD_GAME_JSON_URL')
APPLICATION_ID = os.environ.get('APPLICATION_ID')
ENABLE_SLASH_COMMAND_GUILD_ID = split_guild_env(os.environ.get('ENABLE_SLASH_COMMAND_GUILD_ID'))
USE_IF_AVAILABLE_FILE = if_env(os.environ.get('USE_IF_AVAILABLE_FILE'))
USE_IF_AVAILABLE_FILE = if_env(os.environ.get('USE_IF_AVAILABLE_FILE'))
USE_TWITTER_EXPANDED = if_env_defalut_true(os.environ.get('USE_TWITTER_EXPANDED'))
117 changes: 111 additions & 6 deletions cogs/onmessagecog.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,26 @@
import discord
import os
import re
import aiohttp
import locale
import datetime
from discord.ext import commands # Bot Commands Frameworkのインポート
from logging import getLogger
from datetime import timedelta, timezone
from .modules.savefile import SaveFile
from .modules import settings
from .modules.scrapboxsidandpnames import ScrapboxSidAndPnames
from logging import getLogger

LOG = getLogger('assistantbot')

# コグとして用いるクラスを定義。
class OnMessageCog(commands.Cog, name="メッセージイベント用"):
FILEPATH = 'modules/files/temp'
TWITTER_URL = 'https://twitter.com/'
TWITTER_OR_X_URL = 'https://(?:(?:twitter)|x)\.com/'
TWITTER_STATUS_URL = TWITTER_OR_X_URL + '.+?/status/(\d+)'
TWITTER_EXPAND_URL = 'https://cdn.syndication.twimg.com/tweet-result?token=x&id='
JST = timezone(timedelta(hours=9), 'JST')

# OnMessageCogクラスのコンストラクタ。Botを受取り、インスタンス変数として保持。
def __init__(self, bot):
Expand Down Expand Up @@ -49,6 +58,7 @@ async def save_message_file(self, targetMessage: discord.Message):
return

embeds = []
before_embeds_url = ''
for embed in targetMessage.embeds:
current_path = os.path.dirname(os.path.abspath(__file__))
saved_path = ''.join([current_path, os.sep, self.FILEPATH.replace('/', os.sep)])
Expand All @@ -63,18 +73,19 @@ async def save_message_file(self, targetMessage: discord.Message):
# LOG.debug(embed.image)
# LOG.debug('filepath:' + saved_path)
LOG.info(dicted_data)
if img_url:
if img_url is not None and before_embeds_url != img_url:
path = await self.savefile.download_file_to_dir(img_url, saved_path)
before_embeds_url = img_url.replace(':large','')
if path is not None:
embed_data = discord.Embed()
embed_data.set_thumbnail(url=f'attachment://{path}')
embed_data = discord.Embed(url='https://discord.com')
embed_data.set_image(url=f'attachment://{path}')
embeds.append(embed_data)
full_path = saved_path + os.sep + path
files.append(discord.File(full_path, filename=path))
LOG.debug('save file: ' + full_path)
else:
LOG.debug('url is empty.')
return
continue

# チャンネルにファイルを添付する
if (len(files) > 0):
Expand All @@ -90,11 +101,18 @@ async def save_message_file(self, targetMessage: discord.Message):
@commands.Cog.listener()
async def on_message(self, message: discord.Message):
botUser = self.bot.user
save_file_message_target = ''

if message.author == botUser:# 自分は無視する
return

# Twitter展開機能(デフォルト:TRUE)
if settings.USE_TWITTER_EXPANDED:
# Twitter展開(対象あり、かつ、embedsがない(Discordによる展開がない))
reSearch = re.compile(self.TWITTER_STATUS_URL).search(message.clean_content)
if reSearch is not None and len(reSearch.groups()) > 0 and len(message.embeds) == 0:
if type(reSearch.group(1)) is str:
await self.twitter_url_expand(message, reSearch.group(1))

if self.scrapboxSidAndPnames.SCRAPBOX_URL_PATTERN in message.clean_content and self.scrapboxSidAndPnames.setup(message.guild):
await self.scrapbox_url_expand(message)
else:
Expand All @@ -109,5 +127,92 @@ async def scrapbox_url_expand(self, targetMessage: discord.Message):
else:
return

# TwitterのURLを展開
async def twitter_url_expand(self, targetMessage: discord.Message, twitter_status_id: str):
url = self.TWITTER_EXPAND_URL + twitter_status_id
async with aiohttp.ClientSession() as session:
async with session.get(url) as r:
LOG.debug(url)
LOG.debug(r.status)
if r.status == 200:
data = await r.json()
LOG.info(await r.text())

# 画像の保存
files = []
embeds = []
image_paths = []
thumbnail_url = None
if data.get('mediaDetails') is not None:
for media in data.get('mediaDetails'):
if media.get('media_url_https') is not None:
thumbnail_url = media.get('media_url_https')
current_path = os.path.dirname(os.path.abspath(__file__))
saved_path = ''.join([current_path, os.sep, self.FILEPATH.replace('/', os.sep)])
path = await self.savefile.download_file_to_dir(thumbnail_url, saved_path)
if path is not None:
full_path = saved_path + os.sep + path
files.append(discord.File(full_path, filename=path))
image_paths.append(path)

screen_name = data.get('user').get('screen_name')
title_text = f'''{data.get('user').get('name')}(id:{data.get('user').get('id_str')}) by Twitter'''
description_text = data.get('text')
target_url = f'''{self.TWITTER_URL}{screen_name}/status/{twitter_status_id}'''
twitter_profile_url = self.TWITTER_URL + screen_name

# debug
list = [screen_name,title_text,description_text,target_url,twitter_profile_url]
for item in list:
LOG.info(item)

embed = discord.Embed(
title=title_text
, color=0x1da1f2
, description=description_text
, url=target_url
)
embed.set_author(
name=screen_name
, url=twitter_profile_url
, icon_url=data.get('user').get('profile_image_url_https')
)
if thumbnail_url is not None:
embed.set_thumbnail(url=thumbnail_url)
embed.set_image(url=f'''attachment://{image_paths[0]}''')
embed.add_field(name='投稿日付',value=self.iso8601_to_jst_text(data.get('created_at')))
embed.add_field(name='お気に入り数',value=data.get('favorite_count'))
embed.set_footer(
text='From Twitter'
, icon_url='https://i.imgur.com/NRad4mF.png')

for image_path in image_paths:
embed_data = discord.Embed(url=target_url)
embed_data.set_image(url=f'''attachment://{image_path}''')
embeds.append(embed_data)
else:
if len(embeds) > 0:
embeds[0] = embed
else:
embeds.append(embed)

# 画像あり
if len(files) > 0:
await targetMessage.reply(
'Twitter Expanded',
files=files,
embeds=embeds,
mention_author=False)
else:
await targetMessage.reply(
'Twitter Expanded',
embeds=embeds,
mention_author=False)

def iso8601_to_jst_text(self, iso8601:str):
dt_utc = datetime.datetime.fromisoformat(iso8601.replace('Z', '+00:00')) # python3.11から不要だが...
locale.setlocale(locale.LC_TIME, 'ja_JP.UTF-8')
return dt_utc.astimezone(self.JST).strftime('%Y/%m/%d(%a) %H:%M:%S')

async def setup(bot):
await bot.add_cog(OnMessageCog(bot)) # OnMessageCogにBotを渡してインスタンス化し、Botにコグとして登録する
Loading

0 comments on commit 0ba38a4

Please sign in to comment.