TwitchBot/bot.py

143 lines
6.7 KiB
Python

import os
import json
from random import randrange
from dotenv import load_dotenv
from twitchio.ext import commands
from twitchio.http import TwitchHTTP
from twitchio import PartialUser, Client
def load_config_file():
content = {}
with open('config.json', 'r') as f:
content = json.load(f)
if not content:
content = {'water_limit': 10,
'prime_spam_limit': 15}
save_config_file(content)
return content
def save_config_file(new_content):
with open('config.json', 'w', encoding='utf-8') as f:
json.dump(new_content, f, ident=4)
class Bot(commands.Bot):
count_to_hydrate = 0
count_to_prime_spam = 0
capital_warning = {}
def __init__(self):
super().__init__(token=os.environ['TMI_TOKEN'],
client_id=os.environ['CLIENT_ID'],
nick=os.environ['BOT_NICK'],
prefix=os.environ['BOT_PREFIX'],
initial_channels=[os.environ['CHANNEL']])
self.client = Client(os.environ['TMI_TOKEN'])
self.http = TwitchHTTP(client=self.client, client_id=os.environ['CLIENT_ID'],
client_secret=os.environ['CLIENT_SECRET'])
self.default_values = load_config_file()
async def event_ready(self):
# We are logged in and ready to chat and use commands...
print(f'Logged in as | {self.nick}')
print(f'User id is | {self.user_id}')
await bot.connected_channels[0].send('/me {}'.format(os.environ['ARRIVAL']))
async def event_message(self, ctx, *, user=None):
# Messages with echo set to True are messages sent by the bot...
# For now we just want to ignore them...
if ctx.echo:
return
# Since we have commands and are overriding the default `event_message`
# We must let the bot know we want to handle and invoke our commands...
await self.handle_commands(ctx)
# Replies someone if have written the substring in the if
if 'hola caracola' in ctx.content.lower():
await ctx.channel.send('Hola caracola @{}'.format(ctx.author.display_name))
# For each 100 messages, send one
self.count_to_hydrate += 1
self.count_to_prime_spam += 1
if self.count_to_hydrate == self.default_values['water_limit']:
self.count_to_hydrate = 0
await ctx.channel.send('/me Recordad hidrataros!!')
if self.count_to_prime_spam == self.default_values['prime_spam_limit']:
self.count_to_prime_spam = 0
await ctx.channel.send(
'/me Recordad que si queréis apoyar el directo, podéis utilizar el prime en este canal.')
if ctx.content.isupper() and len(ctx.content) > 5:
# if not ctx.author.is_mod:
if ctx.author.name in self.capital_warning and self.capital_warning[ctx.author.name] < 4:
self.capital_warning[ctx.author.name] += 1
await ctx.channel.send(
'Menos gritos con los gritos @{}. Llevas con este {} avisos por gritar, al quinto '
'te ganas un pequeño timeout'.format(ctx.author.display_name,
self.capital_warning[ctx.author.name]))
elif ctx.author.name in self.capital_warning and self.capital_warning[ctx.author.name] >= 4:
await ctx.channel.send('Quien avisa no es traidor. @{}, el usuario @{} ha gritado varias veces.'.
format(ctx.channel.name, ctx.author.display_name))
# await ctx.channel.timeout(ctx.author.name, 5, "Escribir con mayúsculas varias veces")
# await ctx.channel.send('/timeout {} {} Spamear mayúsculas'.format(ctx.author.display_name, 300))
# ctx.author.channel
# TODO: time_out
# user_to_timeout = PartialUser(http=self.http, id=self.client.user_id, name=self.client.nick)
# await user_to_timeout.timeout_user(token=os.environ['TMI_TOKEN'],
# moderator_id=self.user_id,
# user_id=ctx.author.id, duration=5, reason="Spam de mayúsculas")
# await ctx.author.timeout_user(token=os.environ['TMI_TOKEN'], moderator_id=os.environ['CLIENT_ID'],
# user_id=ctx.author.id, duration=5, reason="Spam de mayúsculas")
# TODO: command to stop the bot
else:
self.capital_warning[ctx.author.name] = 1
await ctx.channel.send('Menos gritos con los gritos @{}. Este es el primer aviso ten '
'cuidado con llegar a 5'.format(ctx.author.display_name))
@commands.command(name='redes')
async def social(self, ctx):
print('\nSending social media...')
await ctx.send('Twitter: {} || Instagram: {} || Instagram de mechas: {} ||'
' Itch: {}'.format(os.environ['TWITTER'],
os.environ['INSTAGRAM'],
os.environ['INSTAGRAM_MECHA'],
os.environ['ITCHIO']))
@commands.command(name='placaje')
async def get_random_chatter(self, ctx):
# print(bot.connected_channels[0].chatters)
print("Tackling...")
list_chatters = list(bot.connected_channels[0].chatters)
random_indx = randrange(0, len(list_chatters) - 1)
if ctx.author.name == list_chatters[random_indx].name:
random_indx = (random_indx + 1) % (len(list_chatters) - 1)
if list_chatters[random_indx] is None:
await ctx.channel.send('{} has fallado el placaje y te caes al barro.'.format(ctx.author.display_name))
else:
await ctx.channel.send('{} manda a China a {} de un placaje'.format(ctx.author.display_name,
list_chatters[random_indx].display_name))
@commands.command(name='reco')
async def send_recommendation(self, ctx, arg):
print("Recommending channel...")
await ctx.channel.send('Pasad a echarle un ojo al canal de https://www.twitch.tv/{}'.format(arg))
@commands.command(name='comandos')
async def my_commands(self, ctx):
print('\nSending my command list...')
await ctx.channel.send('Los comandos disponibles ahora mismo son: !redes, !placaje, !reco. '
'También puedes saludar con un "Hola caracola".')
if __name__ == "__main__":
load_dotenv()
bot = Bot()
bot.run()