Skip to content

Commit

Permalink
V 1.0.0
Browse files Browse the repository at this point in the history
  • Loading branch information
rafaelurben committed Oct 31, 2020
1 parent 790cd07 commit 84e2378
Show file tree
Hide file tree
Showing 11 changed files with 356 additions and 32 deletions.
2 changes: 1 addition & 1 deletion _version.txt
Original file line number Diff line number Diff line change
@@ -1 +1 @@
1.0.0.dev4
1.0.0
3 changes: 2 additions & 1 deletion discordbot/admin.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from django.contrib import admin
from .models import Server, User, Report, Member, AmongUsGame, AMONGUS_PLAYER_COLORS
from .models import Server, User, Report, Member, AmongUsGame, AMONGUS_PLAYER_COLORS, VierGewinntGame

# Register your models here.

Expand Down Expand Up @@ -111,3 +111,4 @@ class AmongUsGameAdmin(admin.ModelAdmin):
def has_add_permission(self, request, obj=None):
return False

admin.site.register(VierGewinntGame)
69 changes: 58 additions & 11 deletions discordbot/botcmds/games.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@
from asgiref.sync import sync_to_async

from discord.ext import commands, tasks
from discord import Embed, utils, PermissionOverwrite, Color, NotFound
from discord import Embed, utils, PermissionOverwrite, Color, NotFound, User

from django.utils import timezone

from datetime import timedelta

from discordbot.models import AmongUsGame, AMONGUS_PLAYER_COLORS, AMONGUS_EMOJI_COLORS
from discordbot.models import AmongUsGame, AMONGUS_PLAYER_COLORS, AMONGUS_EMOJI_COLORS, VierGewinntGame, VIERGEWINNT_NUMBER_EMOJIS
from discordbot.botmodules.serverdata import DjangoConnection

import requests
Expand Down Expand Up @@ -68,7 +68,7 @@ def cog_unload(self):
self.amongus_backgroundtasks.cancel()



# Fortnite

@commands.command(
brief="Erhalte Aktuelles zu Fortnite",
Expand Down Expand Up @@ -131,8 +131,7 @@ async def fortnite(self, ctx, Unterbefehl:str, platform:str="", playername:str="
raise commands.BadArgument(message="Scheinbar ist dieser Befehl nicht richtig konfiguriert.")




# Minecraft

@commands.group(
brief="Hauptcommand für alle Minecraft Befehle",
Expand Down Expand Up @@ -237,8 +236,8 @@ async def minecraft_player(self, ctx, name):





# AmongUs
## AmongUs Tasks

@tasks.loop(seconds=0.5)
async def amongus_backgroundtasks(self):
Expand Down Expand Up @@ -384,13 +383,14 @@ def log(*args):
except Exception as e:
log('Error:', e)


@amongus_backgroundtasks.before_loop
async def amongus_backgroundtasks_before(self):
print('[AmongUs Background Tasks] - Waiting for bot to be ready...')
await self.bot.wait_until_ready()
print('[AmongUs Background Tasks] - Started!')

## AmongUs Commands

@commands.group(
brief="Hauptcommand für alle AmongUs Befehle",
description='Alle AmongUs-Befehle beginnen mit diesem Befehl.',
Expand Down Expand Up @@ -448,7 +448,6 @@ async def amongus_create(self, ctx):
)
await ctx.author.send(embed=embed)


@amongus.command(
name="close",
aliases=['delete', 'del', '-'],
Expand Down Expand Up @@ -487,7 +486,8 @@ async def amongus_reset(self, ctx):
voicechannel = ctx.guild.get_channel(int(game.voice_channel_id))

if voicechannel is not None:
await ctx.database._resetAmongUsGame(game, save=True)
game.reset()
await ctx.database._saveAmongUsGame(game)
await voicechannel.edit(sync_permissions=True)
await ctx.sendEmbed(
title="AmongUs Spiel zurückgesetzt!",
Expand Down Expand Up @@ -521,7 +521,54 @@ async def amongus_apikey(self, ctx):
await ctx.author.send(embed=embed)
else:
raise commands.CommandError("DU hast kein AmongUs Spiel!")



# VierGewinnt

@commands.group(
brief="Hauptcommand für alle VierGewinnt Befehle",
description='Alle VierGewinnt-Befehle beginnen mit diesem Befehl.',
aliases=['fourinarow', '4gewinnt', '4inarow', '4row', '4win'],
help="Um eine Liste aller VierGewinnt-Befehle zu erhalten, gib den Command ohne Argumente ein.",
usage="<Unterbefehl> [Argumente]"
)
@commands.guild_only()
async def viergewinnt(self, ctx):
if ctx.invoked_subcommand is None:
await ctx.sendEmbed(
title="VierGewinnt Befehle",
description=f"""Alle AmongUs Befehle können ebenfalls mit `/viergewinnt` verwendet werden.""",
color=0x0078D7,
inline=False,
fields=[
("/4gewinnt duell <Mitglied>", "Duelliere einen anderen Spieler"),
]
)

@viergewinnt.command(
name="duell",
aliases=['battle', 'duel'],
)
@commands.guild_only()
async def viergewinnt_duell(self, ctx, user:User, width:int=7, height:int=6):
msg = await ctx.sendEmbed(
title="Vier Gewinnt",
color=0x0078D7,
description=f"Duell gegen {user.mention} wird erstellt..."
)

game = await ctx.database._createVierGewinntGame(channel_id=str(ctx.channel.id), message_id=str(msg.id), player_1_id=str(ctx.author.id), player_2_id=str(user.id), width=width, height=height)

embed = ctx.bot.getEmbed(
title=f"Vier Gewinnt (#{game.pk})",
color=0x0078D7,
description=game.get_description()
)

await msg.edit(embed=embed)

for emoji in VIERGEWINNT_NUMBER_EMOJIS[:game.width]:
await msg.add_reaction(emoji)

def setup(bot):
bot.add_cog(Games(bot))
2 changes: 2 additions & 0 deletions discordbot/botcmds/owneronly.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ async def reload(self, ctx, extension:str=None):
msg = await ctx.sendEmbed(title="Reload", color=self.color, fields=[("Status", "Reloading")])
EMBED = ctx.getEmbed(title="Reload", color=self.color, fields=[])
if extension in extensions:
print("[Bot] - Reloading"+extension+"...")
try:
self.bot.unload_extension(extensionfolder+"."+extension)
except:
Expand All @@ -25,6 +26,7 @@ async def reload(self, ctx, extension:str=None):
pass
EMBED.add_field(name="Status",value="Reloaded category "+extension.upper()+"!")
else:
print("[Bot] - Reloading all extensions...")
for extension in extensions:
try:
self.bot.unload_extension(extensionfolder+"."+extension)
Expand Down
37 changes: 32 additions & 5 deletions discordbot/botevents/on_reaction_add.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
from discord import Embed, User, Member, utils, PermissionOverwrite, Role, PCMVolumeTransformer, FFmpegPCMAudio
import os

from discordbot.models import AmongUsGame, AMONGUS_PLAYER_COLORS, AMONGUS_EMOJI_COLORS
from discordbot.models import AmongUsGame, AMONGUS_PLAYER_COLORS, AMONGUS_EMOJI_COLORS, VierGewinntGame, VIERGEWINNT_NUMBER_EMOJIS, VIERGEWINNT_PLAYER_EMOJIS

from discordbot.botmodules.serverdata import DjangoConnection

Expand All @@ -18,18 +18,45 @@ def setup(bot):
@bot.event
async def on_raw_reaction_add(payload):
if not payload.user_id == bot.user.id:
### Games -> AmongUs

emoji = payload.emoji.name
channel = await bot.fetch_channel(payload.channel_id)
message = await channel.fetch_message(payload.message_id)

### Games -> AmongUs

if (emoji in AMONGUS_EMOJI_COLORS or emoji == DELETE) and await DjangoConnection._hasAmongUsGame(text_message_id=payload.message_id):
game = await DjangoConnection._getAmongUsGame(text_message_id=payload.message_id)

if emoji == DELETE:
await DjangoConnection._removeAmongUsUser(game=game, userid=payload.user_id, save=True)
else:
c = AMONGUS_EMOJI_COLORS[payload.emoji.name]
await DjangoConnection._setAmongUsUser(game=game, userid=payload.user_id, color=c, save=True)

channel = await bot.fetch_channel(payload.channel_id)
message = await channel.fetch_message(payload.message_id)
await message.remove_reaction(emoji, payload.member)

### Games -> VierGewinnt

if (emoji in VIERGEWINNT_NUMBER_EMOJIS) and await DjangoConnection._hasVierGewinntGame(message_id=payload.message_id):
game = await DjangoConnection._getVierGewinntGame(message_id=payload.message_id)

if not game.finished:
n = VIERGEWINNT_NUMBER_EMOJIS.index(emoji)

success = game.process(n, payload.user_id)
if success:
await DjangoConnection._saveVierGewinntGame(game)

embed = bot.getEmbed(
title=f"Vier Gewinnt (#{game.pk})",
color=0x0078D7,
description=game.get_description()
)

await message.edit(embed=embed)

if game.finished:
for emoji in VIERGEWINNT_NUMBER_EMOJIS[:game.width]:
await message.remove_reaction(emoji, bot.user)

await message.remove_reaction(emoji, payload.member)
28 changes: 22 additions & 6 deletions discordbot/botmodules/serverdata.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ def getServer(self, serverid:int):

### NEW

from discordbot.models import Server as DB_Server, User as DB_User, Report as DB_Report, Member as DB_Member, AmongUsGame
from discordbot.models import Server as DB_Server, User as DB_User, Report as DB_Report, Member as DB_Member, AmongUsGame, VierGewinntGame

class DjangoConnection():
def __init__(self, dc_user, dc_guild):
Expand Down Expand Up @@ -264,11 +264,6 @@ async def createAmongUsGame(self, **kwargs):
def _saveAmongUsGame(self, game: AmongUsGame):
game.save()

@classmethod
@sync_to_async
def _resetAmongUsGame(self, game: AmongUsGame, save: bool = False):
game.reset(save=save)

@classmethod
@sync_to_async
def _deleteAmongUsGame(self, game: AmongUsGame):
Expand All @@ -284,3 +279,24 @@ def _setAmongUsUser(self, game: AmongUsGame, userid: int, color: str, save: bool
def _removeAmongUsUser(self, game: AmongUsGame, userid: int, save: bool = False):
game.remove_user(userid=userid, save=save)

# VierGewinnt

@classmethod
@sync_to_async
def _getVierGewinntGame(self, **kwargs):
return VierGewinntGame.objects.get(**kwargs)

@classmethod
@sync_to_async
def _hasVierGewinntGame(self, **kwargs):
return VierGewinntGame.objects.filter(**kwargs).exists()

@classmethod
@sync_to_async
def _createVierGewinntGame(self, **kwargs):
return VierGewinntGame.create(**kwargs)

@classmethod
@sync_to_async
def _saveVierGewinntGame(self, game: AmongUsGame):
game.save()
2 changes: 1 addition & 1 deletion discordbot/files/amongus/coords.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,4 @@
print(positionStr, end='')
print('\b' * len(positionStr), end='', flush=True)
except KeyboardInterrupt:
pass
pass
3 changes: 3 additions & 0 deletions discordbot/files/amongus/tracker.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
# 2020 - Rafael Urben
# https://github.com/rafaelurben/django-discordbot/tree/master/discordbot/files/amongus

import json
import threading
import time
Expand Down
36 changes: 36 additions & 0 deletions discordbot/migrations/0010_viergewinntgame.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# Generated by Django 3.1.2 on 2020-10-31 15:15

import discordbot.models
from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('discordbot', '0009_remove_amongusgame_tracker_connected'),
]

operations = [
migrations.CreateModel(
name='VierGewinntGame',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('width', models.PositiveSmallIntegerField(default=7, verbose_name='Width')),
('height', models.PositiveSmallIntegerField(default=6, verbose_name='Height')),
('game', models.JSONField(default=discordbot.models.VIERGEWINNT_DEFAULT_GAME, verbose_name='Game')),
('finished', models.BooleanField(default=False, verbose_name='Finished')),
('current_player', models.PositiveSmallIntegerField(default=1, verbose_name='Current player')),
('player_1_id', models.CharField(max_length=32, verbose_name='Player 1 ID')),
('player_2_id', models.CharField(max_length=32, verbose_name='Player 2 ID')),
('winner_id', models.CharField(default=None, max_length=32, null=True, verbose_name='Winner ID')),
('channel_id', models.CharField(max_length=32, verbose_name='Channel ID')),
('message_id', models.CharField(max_length=32, verbose_name='Message ID')),
('time_created', models.DateTimeField(auto_now_add=True, verbose_name='Time created')),
('time_edited', models.DateTimeField(auto_now=True, verbose_name='Time edited')),
],
options={
'verbose_name': 'VierGewinnt Game',
'verbose_name_plural': 'VierGewinnt Games',
},
),
]
18 changes: 18 additions & 0 deletions discordbot/migrations/0011_auto_20201031_1721.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Generated by Django 3.1.2 on 2020-10-31 16:21

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('discordbot', '0010_viergewinntgame'),
]

operations = [
migrations.AlterField(
model_name='viergewinntgame',
name='player_2_id',
field=models.CharField(default=None, max_length=32, null=True, verbose_name='Player 2 ID'),
),
]
Loading

0 comments on commit 84e2378

Please sign in to comment.