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 # News
- [ ] i18n for messages - [ ] i18n for messages
- [ ] Custom prefixes - [x] Custom prefixes
- [ ] Better help command - [ ] Better help command
- [ ] Alias system for commands (e.g. `.alias .ci show .cs`) - [ ] 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 - [x] Prepare bot for python 3.8 and discord.py 1.3.0
- [ ] Create launcher - [ ] Create launcher
- [ ] Create documentation - [ ] Create documentation
@ -17,7 +17,7 @@
## New commands : ## 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) - [ ] `.sondage --edit <id>` (edit a sondage if we are the author or an admin)
## Documentation: ## Documentation:

16
bot.py
View file

@ -1,17 +1,17 @@
import contextlib
import datetime import datetime
import logging import logging
import sys import sys
from collections import deque, Counter from collections import deque, Counter
from typing import List from typing import List
import contextlib
import aiohttp import aiohttp
import discord import discord
import git import git
from discord.ext import commands from discord.ext import commands
from cogs.utils.database import Database
from cogs.utils.config import Config from cogs.utils.config import Config
from cogs.utils.database import Database
from cogs.utils.lang import Texts from cogs.utils.lang import Texts
from cogs.utils.version import Version from cogs.utils.version import Version
@ -25,11 +25,12 @@ log = logging.getLogger(__name__)
l_extensions: List[str] = [ l_extensions: List[str] = [
'cogs.admin', 'cogs.admin',
'cogs.basics', 'cogs.basics',
'cogs.utility',
'cogs.logs', 'cogs.logs',
'cogs.monitoring',
'cogs.user',
'cogs.utility',
'cogs.poll', 'cogs.poll',
'jishaku', 'jishaku',
'cogs.monitoring'
] ]
@ -114,10 +115,13 @@ class TuxBot(commands.AutoShardedBot):
await self.invoke(ctx) await self.invoke(ctx)
async def on_message(self, message: discord.message): 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 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 return
await self.process_commands(message) await self.process_commands(message)

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -1,6 +1,7 @@
from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base() Base = declarative_base()
from .lang import Lang from .lang import LangModel
from .warn import Warn from .warn import WarnModel
from .poll import Poll, Responses 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 from sqlalchemy import Column, String
class Lang(Base): class LangModel(Base):
__tablename__ = 'langs' __tablename__ = 'langs'
key = Column(String, primary_key=True) key = Column(String, primary_key=True)
value = Column(String) value = Column(String)
def __repr__(self): 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 from sqlalchemy.orm import relationship
class Poll(Base): class PollModel(Base):
__tablename__ = 'polls' __tablename__ = 'polls'
id = Column(Integer, primary_key=True, autoincrement=True) id = Column(Integer, primary_key=True, autoincrement=True)
@ -14,10 +14,10 @@ class Poll(Base):
is_anonymous = Column(Boolean) is_anonymous = Column(Boolean)
available_choices = Column(Integer) available_choices = Column(Integer)
choice = relationship("Responses") choice = relationship("ResponsesModel")
class Responses(Base): class ResponsesModel(Base):
__tablename__ = 'responses' __tablename__ = 'responses'
id = Column(Integer, primary_key=True, autoincrement=True) 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 from sqlalchemy import Column, Integer, String, BIGINT, TIMESTAMP
class Warn(Base): class WarnModel(Base):
__tablename__ = 'warns' __tablename__ = 'warns'
id = Column(Integer, primary_key=True) id = Column(Integer, primary_key=True)
@ -14,6 +14,6 @@ class Warn(Base):
created_at = Column(TIMESTAMP, default=datetime.datetime.now()) created_at = Column(TIMESTAMP, default=datetime.datetime.now())
def __repr__(self): 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')>" \ "created_at='%s')>" \
% (self.server_id, self.user_id, self.reason, self.created_at) % (self.server_id, self.user_id, self.reason, self.created_at)

View file

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

View file

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

View file

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