Skip to content

Commit

Permalink
Merge pull request #14 from tetsuya-ki/develop
Browse files Browse the repository at this point in the history
Developの取り込み
  • Loading branch information
tetsuya-ki authored Jun 3, 2021
2 parents ce3518f + 5288837 commit 088efe8
Show file tree
Hide file tree
Showing 5 changed files with 72 additions and 22 deletions.
13 changes: 12 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@

### `/remind-list`

- 自分がそのギルドで登録したリマインドを表示します
- ギルドで使用すると、自分がそのギルドで登録したリマインドを表示します
- BotとのDMで使用すると、自分が登録したリマインドを表示します

### `/remind-make`

Expand Down Expand Up @@ -54,6 +55,16 @@
- 数字
- あなたが登録したリマインドのNoである必要があります(他人のリマインドはキャンセルできません)

### `/remind-list-guild-all`

- ギルド内のみ、かつ、ギルドの管理者権限保持者のみ使用可能
- そのギルドで登録されているリマインドをすべて表示します

### `/remind-list-all`

- BotとのDMのみ、かつ、Botのオーナーのみ使用可能
- Botに登録されているリマインドをすべて表示します

### その他のコマンドは検討中です(リマインドの削除など実装予定)

## 環境変数
Expand Down
43 changes: 32 additions & 11 deletions cogs/modules/remind.py
Original file line number Diff line number Diff line change
Expand Up @@ -127,20 +127,20 @@ async def set_discord_attachment_file(self, guild):
permissions.append(discord.PermissionOverwrite(read_messages=False,read_message_history=False))
target.append(guild.default_role)
permissions.append(discord.PermissionOverwrite(read_messages=True,read_message_history=True))
target.append(guild.owner)
permissions.append(discord.PermissionOverwrite(read_messages=True,read_message_history=True))
target.append(self.bot.user)
overwrites = dict(zip(target, permissions))

try:
get_control_channel = await guild.create_text_channel(name=self.REMIND_CONTROL_CHANNEL, overwrites=overwrites)
# get_control_channel = await guild.create_text_channel(name=self.REMIND_CONTROL_CHANNEL)
LOG.info(f'***{self.REMIND_CONTROL_CHANNEL}を作成しました!***')
except discord.errors.Forbidden:
LOG.error(f'***{self.REMIND_CONTROL_CHANNEL}の作成に失敗しました!***')
msg = f'***{self.REMIND_CONTROL_CHANNEL}の作成に失敗しました!***'
LOG.error(msg)
raise

if get_control_channel is None:
LOG.error(f'なんらかのエラーが発生しました')
return

# チャンネルの最後のメッセージを確認し、所定のメッセージなら削除する
last_message = await get_control_channel.history(limit=1).flatten()
Expand Down Expand Up @@ -172,9 +172,11 @@ def read(self):
with conn:
cur = conn.cursor()
select_sql = '''select * from reminder_table where status = 'Progress' order by remind_datetime'''
LOG.debug(select_sql)
cur.execute(select_sql)
self.remind_rows = cur.fetchmany(100)
LOG.info(f'******読み込みが完了しました******\n{self.remind_rows}')
LOG.info('******読み込みが完了しました******')
LOG.debug(self.remind_rows)

async def make(self, guild_id, author_id, remind_datetime: datetime,
remind_message: str, channel: int, status: str, repeat_flg: str,
Expand All @@ -195,6 +197,7 @@ async def make(self, guild_id, author_id, remind_datetime: datetime,

# Insert a row of data
cur.execute(insert_sql, remind_param)
LOG.debug(insert_sql)

# get id
get_id_sql = 'select id from reminder_table where rowid = last_insert_rowid()'
Expand All @@ -205,7 +208,6 @@ async def make(self, guild_id, author_id, remind_datetime: datetime,
self.read()
self.encode()
# Herokuの時のみ、チャンネルにファイルを添付する
# self.bot
guild = discord.utils.get(self.bot.guilds, id=guild_id)
await self.set_discord_attachment_file(guild)
return id
Expand All @@ -220,6 +222,7 @@ async def update_status(self, remind_id: int, guild_id: int, status: str=STATUS_

remind_param = (status, now, remind_id)
update_sql = 'update reminder_table set status=?, updated_at = ? where id = ?'
LOG.debug(update_sql)
conn.execute(update_sql, remind_param)
LOG.info(f'id:{remind_id}{status}にしました')
self.read()
Expand All @@ -232,7 +235,12 @@ def list(self, ctx: commands.Context):
conn = sqlite3.connect(self.FILE_PATH)
with conn:
cur = conn.cursor()
select_sql = f'''select * from reminder_table where status = 'Progress' and guild = '{ctx.guild.id}' and member = '{ctx.author.id}' order by remind_datetime'''
if ctx.guild is None:
select_sql = f'''select * from reminder_table where status = 'Progress' and member = '{ctx.author.id}' order by remind_datetime'''
else:
select_sql = f'''select * from reminder_table where status = 'Progress' and guild = '{ctx.guild.id}' and member = '{ctx.author.id}' order by remind_datetime'''

LOG.debug(select_sql)
cur.execute(select_sql)
rows = cur.fetchmany(100)
message = ''
Expand All @@ -244,16 +252,28 @@ def list(self, ctx: commands.Context):
message += f'Status: {row[6]} {repeat_message}{repeat_interval_message}\n--\n'

escaped_mention_text = '(データがありません)' if len(message) == 0 else discord.utils.escape_mentions(message)
LOG.info(escaped_mention_text)
LOG.debug(escaped_mention_text)
self.encode()
return escaped_mention_text

def list_all_guild(self, ctx: commands.Context):
return self._list_all_func(ctx, True)

def list_all(self, ctx: commands.Context):
return self._list_all_func(ctx, False)

def _list_all_func(self, ctx: commands.Context, is_guild: bool):
self.decode()
conn = sqlite3.connect(self.FILE_PATH)
with conn:
cur = conn.cursor()
select_sql = 'select * from reminder_table order by updated_at desc'

select_sql = 'select * from reminder_table '
if is_guild:
select_sql += f'''where guild = '{ctx.guild.id}' '''
select_sql += 'order by updated_at desc'
LOG.debug(select_sql)

cur.execute(select_sql)
rows = cur.fetchmany(100)
message = ''
Expand All @@ -264,7 +284,7 @@ def list_all(self, ctx: commands.Context):
message += f'Message: {row[5]}\n'
message += f'Status: {row[6]} {repeat_message}{repeat_interval_message}\n--\n'
escaped_mention_text = '(データがありません)' if len(message) == 0 else discord.utils.escape_mentions(message)
LOG.info(escaped_mention_text)
LOG.debug(escaped_mention_text)
self.encode()
chopped_escaped_mention_text = escaped_mention_text[:1900] + ('...(省略)...' if escaped_mention_text[1900:] else '')
return chopped_escaped_mention_text
Expand All @@ -275,9 +295,10 @@ def get(self, ctx: commands.Context, id: int):
with conn:
cur = conn.cursor()
select_sql = f'''select * from reminder_table where status = 'Progress' and member = '{ctx.author.id}' and id = '{id}' '''
LOG.debug(select_sql)
cur.execute(select_sql)
row = cur.fetchone()
escaped_mention_text = '(データがありません)' if row is None else discord.utils.escape_mentions(str(row))
LOG.info(escaped_mention_text)
LOG.debug(escaped_mention_text)
self.encode()
return row
27 changes: 19 additions & 8 deletions cogs/remindercog.py
Original file line number Diff line number Diff line change
Expand Up @@ -98,9 +98,10 @@ async def printer(self):
else:
break

@commands.guild_only()
@cog_ext.cog_slash(
name="remind-make",
guild_ids=guilds,
# guild_ids=guilds,
description='remindを作成する',
options=[
manage_commands.create_option(name='date',
Expand Down Expand Up @@ -151,7 +152,7 @@ async def _remind_make(self,
else:
channel_id = temp_channel.id

today = datetime.date.today()
today = datetime.datetime.now(self.JST).date()
# 4桁の数字がない場合、先頭に付けてみる
nothing_year = re.search('\d{4}', date) is None
if '-' in date and nothing_year:
Expand Down Expand Up @@ -193,7 +194,7 @@ async def _remind_make(self,

@cog_ext.cog_slash(
name="remind-cancel",
guild_ids=guilds,
# guild_ids=guilds,
description='remindをキャンセルする',
options=[
manage_commands.create_option(name='cancel_no',
Expand All @@ -211,7 +212,7 @@ async def remind_cancel(self,
await ctx.send(invalid_number_msg)
LOG.info(invalid_number_msg)
return

# コマンド実行者が指定したNoのリマインドを持っているかチェック
id = int(cancel_no)
row = self.remind.get(ctx, id)
Expand All @@ -228,19 +229,29 @@ async def remind_cancel(self,
LOG.info(cancel_msg)

@cog_ext.cog_slash(name="remind-list",
guild_ids=guilds,
# guild_ids=guilds,
description='remindを確認する')
async def remind_list(self, ctx):
LOG.info('remindをlistするぜ!')
rows = self.remind.list(ctx)
await ctx.send(content=rows)

@commands.guild_only()
@commands.has_permissions(administrator=True)
@cog_ext.cog_slash(name="remind-list-guild-all",
# guild_ids=guilds,
description='<注意>サーバーのremindをぜんぶ確認する(administrator権限保持者のみ実行可能です!)')
async def _remind_list_guild_all(self, ctx):
LOG.info('remindをlist(guild)するぜ!')
rows = self.remind.list_all_guild(ctx)
await ctx.send(content=rows)

@commands.dm_only()
@commands.is_owner()
@cog_ext.cog_slash(name="remind-list-all",
guild_ids=guilds,
description='<注意>remindをぜんぶ確認する(administrator権限保持者のみ実行可能です!)')
description='<注意>remindをぜんぶ確認する(BotのオーナーのみDMで実行可能です!)')
async def _remind_list_all(self, ctx):
LOG.info('remindをlistするぜ!')
LOG.info('remindをlist(owner)するぜ!')
rows = self.remind.list_all(ctx)
await ctx.send(content=rows)

Expand Down
9 changes: 8 additions & 1 deletion discord-reminderbot.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from cogs.modules import setting
from discord.ext import commands
from discord_slash import SlashCommand
# from discord_slash.utils import manage_commands # for delete slash command
from logging import basicConfig, getLogger, StreamHandler, FileHandler, Formatter, NOTSET
from datetime import timedelta, timezone
import discord, os, datetime
Expand Down Expand Up @@ -52,12 +53,18 @@ def __init__(self, command_prefix, intents):

async def on_ready(self):
LOG.info('We have logged in as {0.user}'.format(self))
##### for delete slash command #####
# guilds = [] if setting.ENABLE_SLASH_COMMAND_GUILD_ID_LIST is None else list(
# map(int, setting.ENABLE_SLASH_COMMAND_GUILD_ID_LIST.split(';')))
# for guild in guilds:
# await manage_commands.remove_all_commands_in(self.user.id, setting.DISCORD_TOKEN, guild)
# LOG.info('remove all guild command for {0}.'.format(guild))

# discord-reminderbotbのインスタンス化、および、起動処理
if __name__ == '__main__':
intents = discord.Intents.all()
intents.typing = False
# intents.members = False # permissionsを使ってチャンネル作成ではこの特権IntentをTrueにする必要があった
intents.members = False
intents.presences = False

bot = DiscordReminderBot(command_prefix='/', intents=intents)
Expand Down
2 changes: 1 addition & 1 deletion poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 088efe8

Please sign in to comment.