Initial commit

This commit is contained in:
Joan Cano
2023-04-19 15:59:20 +02:00
parent 760a3bd4e4
commit 3058a69535
5 changed files with 127 additions and 0 deletions

1
.gitignore vendored Normal file
View File

@@ -0,0 +1 @@
.env

11
docker-compose.yml Normal file
View File

@@ -0,0 +1,11 @@
version: "3"
services:
tesla-raffle:
build: tesla-raffle
image: tesla-raffle:latest
container_name: tesla-raffle
restart: unless-stopped
environment:
- TELEGRAM_TOKEN=${TELEGRAM_TOKEN}
- ADMINISTRADORES=${ADMINISTRADORES}

9
tesla-raffle/Dockerfile Normal file
View File

@@ -0,0 +1,9 @@
FROM python:3.7
RUN mkdir /app
ADD . /app
RUN pip install -r /app/requirements.txt
WORKDIR /app
CMD [ "python", "/app/tesla-raffle.py" ]

View File

@@ -0,0 +1 @@
python-telegram-bot==20.1

View File

@@ -0,0 +1,105 @@
import logging
import random
import os
from telegram import Update
from telegram.ext import (
Application,
CommandHandler,
ContextTypes,
MessageHandler,
filters
)
TELEGRAM_TOKEN = os.getenv("TELEGRAM_TOKEN")
LISTA_ADMINISTRADORES = os.getenv("ADMINISTRADORES")
ADMINISTRADORES = []
for admin in LISTA_ADMINISTRADORES.split(','):
ADMINISTRADORES.append(int(admin))
SORTEO_ACTIVO = False
# Enable logging
logging.basicConfig(
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.INFO
)
logger = logging.getLogger(__name__)
async def finaliza_sorteo(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
# Solo hacemos caso si el usuario es válido
if update.message.from_user.id not in ADMINISTRADORES:
logging.info(f"{update.message.from_user} no está validado")
return
global SORTEO_ACTIVO
# Dejamos de leer mensajes
SORTEO_ACTIVO = False
logging.info("Sorteo finalizado, dejando de leer mensajes.")
logging.info("Escogiendo ganador al azar.")
await context.bot.send_message(chat_id=update.effective_chat.id, text="El sorteo ha finalizado, escogiendo un ganador...")
# Escoge un ganador al azar
if "participantes" in context.chat_data:
if len(context.chat_data["participantes"]) > 0:
ganador = random.choice(context.chat_data["participantes"])
logging.info(f"Ganador: @{ganador}")
await context.bot.send_message(chat_id=update.effective_chat.id, text=f"¡Felicidades @{ganador}! Eres el ganador del sorteo.")
else:
logging.info("Nadie ha participado.")
await context.bot.send_message(chat_id=update.effective_chat.id, text="Nadie ha participado en el sorteo.")
else:
logging.info("Nadie ha participado.")
await context.bot.send_message(chat_id=update.effective_chat.id, text="Nadie ha participado en el sorteo.")
# Se borra la lista de participantes para la próxima
if "participantes" in context.chat_data:
del context.chat_data["participantes"]
async def sorteo(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
# Solo hacemos caso si el usuario es válido
if update.message.from_user.id not in ADMINISTRADORES:
logging.info(f"{update.message.from_user} no está validado")
return
logging.info("Empezando sorteo")
global SORTEO_ACTIVO
# Empezamos a leer mensajes
SORTEO_ACTIVO = True
# Si ya existía una lista de participantes, nos aseguramos de borrarla
if "participantes" in context.chat_data:
del context.chat_data["participantes"]
logging.info("Sorteo activo, leyendo mensajes")
await context.bot.send_message(chat_id=update.effective_chat.id, text="¡Empieza el sorteo! Escribe 'Tengo un Tesla y quiero un referido' para participar.")
async def handle_message(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
global SORTEO_ACTIVO
# Leemos mensajes solo si el sorteo está activo
if SORTEO_ACTIVO:
logging.info(f"Mensaje recibido de '@{update.message.from_user.username}' con el siguiente texto: '{update.message.text}'")
# Inicializamos lista de participantes vacía
if "participantes" not in context.chat_data:
context.chat_data["participantes"] = []
# Solo le hacemos caso a los mensajes que contengan la frase del concurso
if "tengo un tesla y quiero un referido" in update.message.text.lower():
# Si el usuario ya está participando, no lo volvemos a añadir
if update.message.from_user.username not in context.chat_data["participantes"]:
context.chat_data["participantes"].append(update.message.from_user.username)
await update.message.reply_text(f"¡@{update.message.from_user.username} has sido añadido al sorteo!")
else:
await update.message.reply_text(f"¡@{update.message.from_user.username} ya estabas añadido en el sorteo!")
async def id(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
logging.info(f"@{update.message.from_user.username} : {update.message.from_user.id}")
def main()->None:
logging.info(ADMINISTRADORES)
"""Start the bot."""
application = Application.builder().get_updates_http_version('1.1').http_version('1.1').token(TELEGRAM_TOKEN).build()
application.add_handler(CommandHandler("sorteo", sorteo))
application.add_handler(CommandHandler("finaliza", finaliza_sorteo))
application.add_handler(CommandHandler("id", id))
application.add_handler(MessageHandler(filters.TEXT & (~filters.COMMAND), handle_message))
application.run_polling()
if __name__ == "__main__":
main()