start development of alias command

This commit is contained in:
Romain J 2019-12-30 00:48:11 +01:00
parent 64b092dff2
commit d94775e0e6
17 changed files with 177 additions and 66 deletions

View file

@ -1,10 +1,10 @@
# News
- [ ] i18n for messages
- [ ] Custom prefixes
- [x] Custom prefixes
- [ ] Better help command
- [ ] Alias system for commands (e.g. `.alias .ci show .cs`)
- [ ] Migrate MySQL to postgresql
- [x] Migrate MySQL to postgresql
- [x] Prepare bot for python 3.8 and discord.py 1.3.0
- [ ] Create launcher
- [ ] Create documentation
@ -17,7 +17,7 @@
## New commands :
- [ ] `.sondage --anonyme <...>` (create à sondage with the possibility of answering anonymously)
- [x] `.sondage --anonyme <...>` (create à sondage with the possibility of answering anonymously)
- [ ] `.sondage --edit <id>` (edit a sondage if we are the author or an admin)
## Documentation:

16
bot.py
View file

@ -1,17 +1,17 @@
import contextlib
import datetime
import logging
import sys
from collections import deque, Counter
from typing import List
import contextlib
import aiohttp
import discord
import git
from discord.ext import commands
from cogs.utils.database import Database
from cogs.utils.config import Config
from cogs.utils.database import Database
from cogs.utils.lang import Texts
from cogs.utils.version import Version
@ -25,11 +25,12 @@ log = logging.getLogger(__name__)
l_extensions: List[str] = [
'cogs.admin',
'cogs.basics',
'cogs.utility',
'cogs.logs',
'cogs.monitoring',
'cogs.user',
'cogs.utility',
'cogs.poll',
'jishaku',
'cogs.monitoring'
]
@ -114,10 +115,13 @@ class TuxBot(commands.AutoShardedBot):
await self.invoke(ctx)
async def on_message(self, message: discord.message):
if message.author.id in self.blacklist or (message.guild is not None and message.guild.id in self.blacklist):
if message.author.id in self.blacklist \
or (message.guild is not None
and message.guild.id in self.blacklist):
return
if message.author.bot and message.author.id != int(self.config.get('bot', 'Tester')):
if message.author.bot and message.author.id != int(
self.config.get('bot', 'Tester')):
return
await self.process_commands(message)

View file

@ -11,7 +11,7 @@ from discord.ext import commands
from bot import TuxBot
from .utils.lang import Texts
from .utils.extra import commandExtra, groupExtra
from .utils.models import Warn, Lang
from .utils.models import WarnModel, LangModel
log = logging.getLogger(__name__)
@ -257,16 +257,16 @@ class Admin(commands.Cog):
if member:
warns = self.bot.database.session \
.query(Warn) \
.filter(Warn.user_id == member.id, Warn.created_at > week_ago,
Warn.server_id == ctx.guild.id) \
.order_by(Warn.created_at.desc())
.query(WarnModel) \
.filter(WarnModel.user_id == member.id, WarnModel.created_at > week_ago,
WarnModel.server_id == ctx.guild.id) \
.order_by(WarnModel.created_at.desc())
else:
warns = self.bot.database.session \
.query(Warn) \
.filter(Warn.created_at > week_ago,
Warn.server_id == ctx.guild.id) \
.order_by(Warn.created_at.desc())
.query(WarnModel) \
.filter(WarnModel.created_at > week_ago,
WarnModel.server_id == ctx.guild.id) \
.order_by(WarnModel.created_at.desc())
warns_list = ''
for warn in warns:
@ -286,7 +286,7 @@ class Admin(commands.Cog):
reason):
now = datetime.datetime.now()
warn = Warn(server_id=ctx.guild.id, user_id=member.id, reason=reason,
warn = WarnModel(server_id=ctx.guild.id, user_id=member.id, reason=reason,
created_at=now)
self.bot.database.session.add(warn)
@ -389,8 +389,8 @@ class Admin(commands.Cog):
description=Texts('commands').get('admin._warn_remove'))
async def _warn_remove(self, ctx: commands.Context, warn_id: int):
warn = self.bot.database.session \
.query(Warn) \
.filter(Warn.id == warn_id) \
.query(WarnModel) \
.filter(WarnModel.id == warn_id) \
.one()
self.bot.database.session.delete(warn)
@ -414,8 +414,8 @@ class Admin(commands.Cog):
description=Texts('commands').get('admin._warn_edit'))
async def _warn_edit(self, ctx: commands.Context, warn_id: int, *, reason):
warn = self.bot.database.session \
.query(Warn) \
.filter(Warn.id == warn_id) \
.query(WarnModel) \
.filter(WarnModel.id == warn_id) \
.one()
warn.reason = reason
@ -431,8 +431,8 @@ class Admin(commands.Cog):
description=Texts('commands').get('admin._language'))
async def _language(self, ctx: commands.Context, locale: str):
available = self.bot.database.session \
.query(Lang.value) \
.filter(Lang.key == 'available') \
.query(LangModel.value) \
.filter(LangModel.key == 'available') \
.first()[0] \
.split(',')
@ -441,15 +441,15 @@ class Admin(commands.Cog):
Texts('admin', ctx).get('Unable to find this language'))
else:
current = self.bot.database.session \
.query(Lang) \
.filter(Lang.key == str(ctx.guild.id))
.query(LangModel) \
.filter(LangModel.key == str(ctx.guild.id))
if current.count() > 0:
current = current.one()
current.value = locale.lower()
self.bot.database.session.commit()
else:
new_row = Lang(key=str(ctx.guild.id), value=locale.lower())
new_row = LangModel(key=str(ctx.guild.id), value=locale.lower())
self.bot.database.session.add(new_row)
self.bot.database.session.commit()

View file

@ -1,3 +1,4 @@
import logging
import os
import pathlib
import platform
@ -13,6 +14,8 @@ from .utils.lang import Texts
from .utils.extra import commandExtra
from tcp_latency import measure_latency
log = logging.getLogger(__name__)
class Basics(commands.Cog):

View file

@ -1,4 +1,5 @@
import asyncio
import logging
import threading
from aiohttp import web
@ -7,6 +8,8 @@ from aiohttp.web_request import Request
from discord.ext import commands
from bot import TuxBot
log = logging.getLogger(__name__)
class Monitoring(commands.Cog):

View file

@ -1,4 +1,5 @@
import json
import logging
from typing import Union
import discord
@ -7,21 +8,23 @@ from yarl import URL
from bot import TuxBot
from .utils.lang import Texts
from .utils.models import Poll, Responses
from .utils.models import PollModel, ResponsesModel
from .utils.extra import groupExtra
from .utils import emotes as utils_emotes
log = logging.getLogger(__name__)
class Polls(commands.Cog):
def __init__(self, bot: TuxBot):
self.bot = bot
def get_poll(self, pld) -> Union[bool, Poll]:
def get_poll(self, pld) -> Union[bool, PollModel]:
if pld.user_id != self.bot.user.id:
poll = self.bot.database.session \
.query(Poll) \
.filter(Poll.message_id == pld.message_id)
.query(PollModel) \
.filter(PollModel.message_id == pld.message_id)
if poll.count() > 0:
poll = poll.one()
@ -50,11 +53,11 @@ class Polls(commands.Cog):
pass
choice = utils_emotes.get_index(pld.emoji.name)
responses = self.bot.database.session.query(Responses) \
responses = self.bot.database.session.query(ResponsesModel) \
.filter(
Responses.poll_id == poll.id,
Responses.user == pld.user_id,
Responses.choice == choice
ResponsesModel.poll_id == poll.id,
ResponsesModel.user == pld.user_id,
ResponsesModel.choice == choice
)
if responses.count() != 0:
@ -62,7 +65,7 @@ class Polls(commands.Cog):
self.bot.database.session.delete(response)
self.bot.database.session.commit()
else:
response = Responses(
response = ResponsesModel(
user=pld.user_id,
poll_id=poll.id,
choice=choice
@ -79,11 +82,11 @@ class Polls(commands.Cog):
if poll:
choice = utils_emotes.get_index(pld.emoji.name)
responses = self.bot.database.session.query(Responses) \
responses = self.bot.database.session.query(ResponsesModel) \
.filter(
Responses.poll_id == poll.id,
Responses.user == pld.user_id,
Responses.choice == choice
ResponsesModel.poll_id == poll.id,
ResponsesModel.user == pld.user_id,
ResponsesModel.choice == choice
)
if responses.count() != 0:
@ -101,7 +104,7 @@ class Polls(commands.Cog):
stmt = await ctx.send(Texts('poll', ctx).get('**Preparation...**'))
poll_row = Poll()
poll_row = PollModel()
self.bot.database.session.add(poll_row)
self.bot.database.session.flush()
@ -131,8 +134,8 @@ class Polls(commands.Cog):
async def update_poll(self, poll_id: int):
poll = self.bot.database.session \
.query(Poll) \
.filter(Poll.id == poll_id) \
.query(PollModel) \
.filter(PollModel.id == poll_id) \
.one()
channel: discord.TextChannel = self.bot.get_channel(poll.channel_id)
message: discord.Message = await channel.fetch_message(poll.message_id)
@ -154,8 +157,8 @@ class Polls(commands.Cog):
if isinstance(poll.content, str) \
else poll.content
raw_responses = self.bot.database.session\
.query(Responses)\
.filter(Responses.poll_id == poll_id)
.query(ResponsesModel)\
.filter(ResponsesModel.poll_id == poll_id)
responses = {}
for response in raw_responses.all():

66
cogs/user.py Normal file
View file

@ -0,0 +1,66 @@
import logging
from discord.ext import commands
from bot import TuxBot
from .utils.extra import groupExtra
from .utils.lang import Texts
from .utils.models import AliasesModel
log = logging.getLogger(__name__)
class User(commands.Cog):
def __init__(self, bot: TuxBot):
self.bot = bot
###########################################################################
@groupExtra(name='alias', aliases=['aliases'], category='user',
description=Texts('commands').get('user._alias'))
async def _alias(self, ctx: commands.Context):
if ctx.invoked_subcommand is None:
await ctx.send_help('alias')
@_alias.command(name='add', aliases=['set', 'new'],
description=Texts('commands').get('user._alias_add'))
async def _alias_add(self, ctx: commands.Context, *, user_alias: str):
is_global = False
if '--global' in user_alias:
is_global = True
user_alias.replace('--global', '')
user_alias = user_alias.split(' -> ')
if len(user_alias) != 2:
return await ctx.send_help('alias')
command = user_alias[1]
user_alias = user_alias[0]
if self.bot.get_command(command) is None:
return await ctx.send(Texts('user').get('Command not found'))
alias = AliasesModel(
user_id=ctx.author.id,
alias=user_alias,
command=command,
guild="global" if is_global else str(ctx.guild.id)
)
self.bot.database.session.add(alias)
self.bot.database.session.commit()
@_alias.command(name='remove', aliases=['drop', 'del', 'delete'],
description=Texts('commands').get('user._alias_remove'))
async def _alias_remove(self, ctx: commands.Context, prefix: str):
...
@_alias.command(name='list', aliases=['show', 'all'],
description=Texts('commands').get('user._alias_list'))
async def _alias_list(self, ctx: commands.Context):
...
def setup(bot: TuxBot):
bot.add_cog(User(bot))

View file

@ -1,3 +1,4 @@
import logging
import re
import aiohttp
@ -7,11 +8,11 @@ from bot import TuxBot
import socket
from socket import AF_INET6
from .admin import Admin
from .utils.lang import Texts
from .utils.extra import commandExtra
log = logging.getLogger(__name__)
class Utility(commands.Cog):

View file

@ -2,7 +2,7 @@ import gettext
from .config import Config
from cogs.utils.database import Database
from .models.lang import Lang
from .models.lang import LangModel
from discord.ext import commands
@ -26,13 +26,13 @@ class Texts:
if ctx is not None:
current = database.session\
.query(Lang.value)\
.filter(Lang.key == str(ctx.guild.id))
.query(LangModel.value)\
.filter(LangModel.key == str(ctx.guild.id))
if current.count() > 0:
return current.one()[0]
default = database.session\
.query(Lang.value)\
.filter(Lang.key == 'default')\
.query(LangModel.value)\
.filter(LangModel.key == 'default')\
.one()[0]
return default

View file

@ -1,6 +1,7 @@
from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
from .lang import Lang
from .warn import Warn
from .poll import Poll, Responses
from .lang import LangModel
from .warn import WarnModel
from .poll import PollModel, ResponsesModel
from .alias import AliasesModel

View file

@ -0,0 +1,28 @@
from sqlalchemy import Column, String, BigInteger, Integer
from . import Base
class AliasesModel(Base):
__tablename__ = 'aliases'
id = Column(Integer, primary_key=True)
user_id = Column(BigInteger)
alias = Column(String)
command = Column(String)
guild = Column(String)
def __repr__(self):
return "<AliasesModel(" \
"id='%s', " \
"user_id='%s', " \
"alias='%s', " \
"command='%s', " \
"guild='%s', " \
")>" % (
self.id,
self.user_id,
self.alias,
self.command,
self.guild
)

View file

@ -2,11 +2,11 @@ from . import Base
from sqlalchemy import Column, String
class Lang(Base):
class LangModel(Base):
__tablename__ = 'langs'
key = Column(String, primary_key=True)
value = Column(String)
def __repr__(self):
return "<Lang(key='%s', locale='%s')>" % (self.key, self.value)
return "<LangModel(key='%s', locale='%s')>" % (self.key, self.value)

View file

@ -3,7 +3,7 @@ from sqlalchemy import Column, Integer, BigInteger, JSON, ForeignKey, Boolean
from sqlalchemy.orm import relationship
class Poll(Base):
class PollModel(Base):
__tablename__ = 'polls'
id = Column(Integer, primary_key=True, autoincrement=True)
@ -14,10 +14,10 @@ class Poll(Base):
is_anonymous = Column(Boolean)
available_choices = Column(Integer)
choice = relationship("Responses")
choice = relationship("ResponsesModel")
class Responses(Base):
class ResponsesModel(Base):
__tablename__ = 'responses'
id = Column(Integer, primary_key=True, autoincrement=True)

View file

@ -4,7 +4,7 @@ from . import Base
from sqlalchemy import Column, Integer, String, BIGINT, TIMESTAMP
class Warn(Base):
class WarnModel(Base):
__tablename__ = 'warns'
id = Column(Integer, primary_key=True)
@ -14,6 +14,6 @@ class Warn(Base):
created_at = Column(TIMESTAMP, default=datetime.datetime.now())
def __repr__(self):
return "<Warn(server_id='%s', user_id='%s', reason='%s', " \
return "<WarnModel(server_id='%s', user_id='%s', reason='%s', " \
"created_at='%s')>" \
% (self.server_id, self.user_id, self.reason, self.created_at)

View file

@ -13,3 +13,5 @@ prefixes = ba.
[274247231534792704]
prefixes = test.
[528679953399676938]
prefixes = test.

View file

@ -45,7 +45,7 @@ msgstr ""
msgid "Reason"
msgstr ""
msgid "Warn with id"
msgid "WarnModel with id"
msgstr ""
msgid "successfully removed"

View file

@ -45,7 +45,7 @@ msgstr "a recu un avertissement"
msgid "Reason"
msgstr "Raison"
msgid "Warn with id"
msgid "WarnModel with id"
msgstr "L'avertissement avec l'id"
msgid "successfully removed"