Eco_Plus/ecoplus.py
2025-05-12 23:06:57 +02:00

577 lines
18 KiB
Python
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import sys
import random
import datetime
import time
import threading
import asyncio
import discord
import sqlite3
import interface
secrets_file = open(sys.argv[1], mode="rt")
secrets = secrets_file.read()
secrets_file.close()
token = secrets
intents = discord.Intents.default()
intents.message_content = True
intents.members = True
intents.moderation = True
client = discord.Client(intents=intents, activity=discord.Game(name='En train de parier aux courses'))
interface.client = client
import forgejo
database = sqlite3.connect(sys.argv[2])
cursor = database.cursor()
guilds = []
globals()["gmembers"] = {}
async def roll(message):
spec = message.content.split(" ")[1].split("d")
roll = ""
print(spec)
if len(spec) > 1:
d = int(spec[1])
for i in range(int(spec[0])):
roll += str(random.randint(1,d)) + " "
else:
roll += str(random.randint(1,int(spec[0])))
await message.reply(roll)
async def pinguncon(message):
#fcalva's server
if message.guild.id == 750665878072328242:
await message.channel.send("<@499533339468759052>")
elif message.guild.id in [1008485562304450610, 1157767629738618941]:
await message.channel.send("<@755081785393676328>")
elif message.guild.id == 1294017120631525416:
await message.channel.send("<@504751919760408617>")
else:
await message.reply("Pas dispo ici")
async def pingjuif(message):
if message.guild.id in [1008485562304450610, 1157767629738618941]:
await message.channel.send("<@459021187083927553>")
else:
message.channel.reply("Pas dispo ici")
async def pingrand(message):
choice = random.choice(globals()["gmembers"][str(message.guild.id)])
await message.channel.send("<@"+str(choice.id)+">")
async def reload(message):
cursor.execute(f"CREATE TABLE IF NOT EXISTS roulette (gid INT PRIMARY KEY, shots INT)")
gid = int(message.guild.id)
ret = cursor.execute(f"SELECT shots FROM roulette WHERE gid = {gid}").fetchone()
shots = random.randint(0,5)
if ret == None:
cursor.execute(f"INSERT INTO roulette (gid,shots) VALUES ({gid},{shots})")
else:
cursor.execute(f"UPDATE roulette SET shots = {shots} WHERE gid = {gid}")
database.commit()
await message.reply("Revolver rechargé")
async def roulette(message):
cursor.execute(f"CREATE TABLE IF NOT EXISTS roulette (gid INT PRIMARY KEY, shots INT)")
database.commit()
gid = int(message.guild.id)
ret = cursor.execute(f"SELECT shots FROM roulette WHERE gid = {gid}").fetchone()
if ret == None:
shots = random.randint(0,5)
cursor.execute(f"INSERT INTO roulette (gid,shots) VALUES ({gid},{shots})")
database.commit()
else:
shots = ret[0]
print("Shots : ", shots)
if shots <= 0:
tdelt = datetime.timedelta(minutes=5)
uid = message.author.id
try:
await message.author.timeout(tdelt, reason="Vous avez perdu à la roulette...")
await message.channel.send(f"<@{uid}> s'est tiré une balle, et est dans un coma pendant 5 minutes")
except Exception as err:
await message.reply("Une erreur s'est produite : `" + str(err) + "`")
nshots = random.randint(0,5)
cursor.execute(f"UPDATE roulette SET shots = {nshots} WHERE gid = {gid}")
database.commit()
else:
shots -= 1
cursor.execute(f"UPDATE roulette SET shots = {shots} WHERE gid = {gid}")
database.commit()
await message.reply("Clic... il n'y avait pas de cartouche dans la chambre...")
async def casino_init(message):
usrid = int(message.author.id)
gid = int(message.guild.id)
try:
cursor.execute(f"CREATE TABLE IF NOT EXISTS tab_{gid} (id INT PRIMARY KEY, cash INT, lst_coll INT)")
cursor.execute(f"INSERT INTO tab_{gid} (id, cash, lst_coll) VALUES ({usrid}, 0, 0)")
database.commit()
await message.channel.send(f"Casino initialisé pour <@{usrid}>")
except:
await message.reply(f"Échec ! Réessayez plus tard")
init_global_str = "Essayer d'initialiser le casino du serveur avec ?init"
init_perso_str = "Essayez d'initialiser votre portemonnaie avec ?init"
async def balance(message):
usrid = int(message.author.id)
gid = int(message.guild.id)
try:
cash = cursor.execute(f"SELECT cash FROM tab_{gid} WHERE id={usrid}").fetchone()
except:
await message.reply(init_global_str)
if cash != None:
await message.reply(f"Vous avez {cash[0]}$")
else:
await message.reply(init_perso_str)
async def collect(message):
collect_gain = 50
cooldown = 10*60
curr_time = int(time.time())
usrid = int(message.author.id)
gid = int(message.guild.id)
lst_coll = 0
try:
lst_coll = cursor.execute(f"SELECT lst_coll FROM tab_{gid} WHERE id={usrid}").fetchone()[0]
except:
await message.reply(init_perso_str)
return
if lst_coll >= curr_time - cooldown:
rtime = (-curr_time + cooldown + lst_coll)//60
await message.reply(f"Vous pourrez toucher votre RSA dans {rtime} minutes")
return
cash = None
cash = cursor.execute(f"SELECT cash FROM tab_{gid} WHERE id={usrid}").fetchone()
if cash != None:
cash = cash[0]
cash += collect_gain
cursor.execute(f"UPDATE tab_{gid} SET lst_coll = {curr_time} WHERE id={usrid}")
cursor.execute(f"UPDATE tab_{gid} SET cash = {cash} WHERE id={usrid}")
database.commit()
nc = cooldown//60
await message.reply(f"Vous avez recu {collect_gain}$ en RSA. Vous avez désormais {cash}$\n"\
f"Revenez dans {nc} minutes pour votre prochain chèque")
else:
await message.reply(init_perso_str)
async def slot(message):
amnt = message.content.split(' ')[1]
try:
amnt = int(amnt)
except:
await message.channel.send("Quantité invalide")
return
gid = int(message.guild.id)
uid = int(message.author.id)
ret = cursor.execute(f"SELECT cash FROM tab_{gid} WHERE id={uid}").fetchone()
if ret == None:
await message.reply(init_perso_str)
return
cash = ret[0]
if amnt > cash:
await message.reply("Vous n'avez pas assez d'argent")
return
roll = random.random()
gain = 0
if roll < 1/6:
await message.channel.send(f"<@{uid}> a perdu toute sa mise")
if roll >= 1/6 and roll < 3/6:
gain = int(round(amnt*0.5*random.random()))
await message.channel.send(f"<@{uid}> n'a remporté que {gain}$")
if roll >= 3/6 and roll < 5/6:
gain = int(round(amnt*1.25*random.random()))
await message.channel.send(f"<@{uid}> a réussi à remporter {gain}$")
if roll >= 5/6 and roll < 19/20:
gain = int(round(amnt*0.5 + amnt*1.2*random.random()))
await message.channel.send(f"<@{uid}> a extrait {gain}$ des griffes de la machine")
if roll >= 19/20:
gain = int(round(amnt*4 + amnt*17*random.random()))
await message.channel.send(f"# <@{uid}> JACKPOT ! Vous avez gagné {gain}$ !")
cash -= amnt-gain
cursor.execute(f"UPDATE tab_{gid} SET cash = {cash} WHERE id={uid}")
database.commit()
async def leaderboard(message):
uid = int(message.author.id)
gid = int(message.guild.id)
lb = None
result = cursor.execute(f"SELECT * FROM tab_{gid} ORDER BY cash DESC LIMIT 10").fetchall()
msgstr = "## ===== Leaderboard =====\n"
i = 0
rlen = len(result)
while i < rlen:
uid = result[i][0]
ucash = result[i][1]
msgstr += " "+str(i+1)+f". <@{uid}> - {ucash}$\n"
i += 1
await message.reply(msgstr, allowed_mentions=discord.AllowedMentions().none())
async def transfer(message):
split = message.content.split(" ")
gid = int(message.guild.id)
result = None
tid = 0
uid = int(message.author.id)
utili = cursor.execute(f"SELECT * FROM tab_{gid} WHERE id={uid}").fetchone()
if utili == None:
await message.reply(init_perso_str)
return
try:
tid = int(split[1].strip("<@").rstrip(">"))
except:
await message.reply("Destinataire invalide")
return
target = cursor.execute(f"SELECT * FROM tab_{gid} WHERE id={tid}").fetchone()
if target == None:
await message.reply("Destinataire non initialisé ou inexistant")
return
amnt = 0
try:
amnt = int(split[-1])
except:
await message.reply(f"Quantité non valide (`{split[2]}`)")
return
taxamnt = int(round(amnt*0.05))
if taxamnt < 1:
taxamnt = 1
if amnt + taxamnt > utili[1]:
await message.reply("Vous n'avez pas assez d'argent")
return
ncashu = utili[1] - amnt - taxamnt
ncasht = target[1] + amnt
cursor.execute(f"UPDATE tab_{gid} SET cash={ncashu} WHERE id={uid}")
cursor.execute(f"UPDATE tab_{gid} SET cash={ncasht} WHERE id={tid}")
database.commit()
await message.reply(f"Transfert effectué. Une taxe de 5% ({taxamnt}$) a été prélevée.")
forme_msg = [\
"n'est pas très en forme",\
"va bien",\
"est très remonté",\
"a laissé des seringues vides dans son box",\
]
async def do_course(message):
gid = int(message.guild.id)
nxt_tick = 0
ret = cursor.execute(f"SELECT * FROM courses WHERE gid={gid}").fetchone()
start_time = ret[1]
elaps_time = time.time()-ret[2]
cetape = ret[3]
while True:
ctime = time.time()
detape = 0
if ctime < nxt_tick:
await asyncio.sleep(5)
continue
ret = cursor.execute(f"SELECT * FROM courses WHERE gid={gid}").fetchone()
elaps_time = ctime - ret[2]
if elaps_time > 20 and cetape <= 3:
detape = 1
if elaps_time > 20 and cetape > 3:
detape = 1
if detape:
cetape+=1
itime = int(ctime)
cursor.execute(f"UPDATE courses SET date_der={itime},etape={cetape} WHERE gid={gid}")
database.commit()
if cetape < 3:
select = random.randint(1,10)
choice = cursor.execute(f"SELECT * FROM grid_{gid} WHERE n = {select}").fetchone()
msgchoice = 1
if choice[1] < 6:
msgchoice = 0
if choice[1] >= 6 and choice[1] < 8:
msgchoice = 1
if choice[1] >= 8 and choice[1] < 10:
msgchoice = 2
if choice[1] == 10:
msgchoice = 3
msg = forme_msg[msgchoice]
print(f"Forme : {choice[2]},{msgchoice}")
await message.channel.send(f"La rumeur court que le cheval n°{select} {msg}")
if cetape == 3:
await message.channel.send("## La course a commencé, et les paris sont fermés")
if cetape > 3:
for i in range(10):
chev = cursor.execute(f"SELECT * FROM grid_{gid} WHERE n={i+1}").fetchone()
cpos = chev[2] + chev[1] - random.randint(0,2)
cursor.execute(f"UPDATE grid_{gid} SET pos={cpos} WHERE n={chev[0]}")
grid = cursor.execute(f"SELECT * FROM grid_{gid} ORDER BY pos DESC")
msgstr = "## Grille de la course\n"
gagn = 0
n = 1
for chev in grid:
if chev[0] > 50:
clmp_dist = 50
else:
clmp_dist = chev[0]
msgstr += f"{n} - n°{clmp_dist}, {chev[2]*10}m\n"
n += 1
if chev[2] >= 50 and not gagn:
gagn = chev[0]
if gagn:
msgstr += f"\nLe numéro {gagn} a remporté la course !"
cursor.execute(f"UPDATE courses SET fini = 1,etape=0 WHERE gid = {gid}")
wbets = cursor.execute(f"SELECT * FROM bets_{gid} WHERE pari_n = {gagn}").fetchall()
if wbets:
msgstr += "\n## Pari gagnants :\n"
for bet in wbets:
uid = bet[0]
gain = bet[2]*8
msgstr += f"<@{uid}> remporte {gain}$\n"
play = cursor.execute(f"SELECT * FROM tab_{gid} WHERE id = {uid}").fetchone()
ncash = play[1] + gain
cursor.execute(f"UPDATE tab_{gid} SET cash = {ncash} WHERE id = {uid}")
database.commit()
await message.channel.send(msgstr)
if gagn:
break
nxt_tick += 10
await asyncio.sleep(5)
cursor.execute(f"DROP TABLE bets_{gid}")
cursor.execute(f"DROP TABLE grid_{gid}")
database.commit()
print("Tables de course DROP")
async def course(message):
gid = int(message.guild.id)
uid = int(message.author.id)
cursor.execute(f"CREATE TABLE IF NOT EXISTS courses (gid INT PRIMARY KEY, date INT, date_der INT, etape INT, fini INT)")
try:
cursor.execute(f"CREATE TABLE bets_{gid} (id INT, pari_n INT, pari_qtt INT)")
cursor.execute(f"CREATE TABLE grid_{gid} (n INT PRIMARY KEY, speed INT, pos INT)")
except:
await message.reply("Une course est déja en cours")
return
ctime = int(time.time())
cursor.execute(f"INSERT OR REPLACE INTO courses (gid, date, date_der, etape, fini) VALUES ({gid},{ctime},{ctime},0,0)")
grid=[]
for i in range(10):
grid.append(i+1)
while grid:
n = random.choice(grid)
grid.remove(n)
speed = 5 + random.randint(0,2) + random.randint(0,3)
cursor.execute(f"INSERT INTO grid_{gid} (n,speed,pos) VALUES ({n},{speed},0)")
database.commit()
await message.channel.send(
f"### Course de chevaux lancée par <@{uid}>\n"\
"Vous avez 10min pour placer vos paris avec ?bet"\
)
await do_course(message)
async def bet(message):
gid = int(message.guild.id)
uid = int(message.author.id)
ret = None
try:
ret = cursor.execute(f"SELECT * FROM courses WHERE gid = {gid}").fetchone()
if ret and ret[4]:
ret = None
except:
ret = None
if ret == None:
await message.reply("Aucune course n'est en cours.\n"\
"Lancez une course avec ?course")
return
if ret[3] >= 3:
await message.reply("La course est en cours !")
return
split = message.content.split(" ")
if len(split) < 3:
await message.reply("Vous devez spécifier au moins deux arguments\n"\
"Utilisation : ?bet <n° cheval> <quantité>")
return
n = 0
bet = 0
try:
n = int(split[1])
except:
await message.reply("Numéro invalide")
return
if n < 1 or n > 10:
await message.reply("Numéro invalide")
return
try:
bet = int(split[2])
except:
await message.reply("Quantité invalide")
return
if bet < 1:
await message.reply("Quantité invalide")
return
try:
play = cursor.execute(f"SELECT * FROM tab_{gid} WHERE id={uid}").fetchone()
except:
await message.reply(init_perso_str)
return
if play[1] < bet:
await message.reply("Vous n'avez pas assez d'argent")
return
ncash = play[1] - bet
cursor.execute(f"INSERT INTO bets_{gid} (id, pari_n, pari_qtt) VALUES ({uid},{n},{bet})")
cursor.execute(f"UPDATE tab_{gid} SET cash = {ncash} WHERE id = {uid}")
database.commit()
await message.reply("Pari placé")
async def casino_aide(message):
await message.channel.send("Commandes du casino Eco+\n"\
"?init : initialiser votre portefeuille\n"\
"?collect : Collectez votre revenu\n"\
"?cash : Consultez l'état de vos finances\n"\
"?lb : Consultez le top 5 des joueurs les plus riches\n"
"?transfer @dest <qtt> : Transférez <qtt> dollars à @dest\n"\
" (Une taxe de 5% est appliquée)\n"\
"?slot <qtt> : Jouez à la machine à sous avec une mise de <qtt>\n")
async def ecoaide(message):
await message.channel.send("Eco+, un bot Eco plus pour faire des conneries\n"\
"?pinguncon : Ping le con local\n"\
"?pingunjuif : Ping le juif local\n"\
"?pingrand : Ping un membre aléatoire du serveur\n"\
"?roulette : Jouez à la roulette russe\n"\
"?reload : Réinitialisez la roulette russe\n"\
"?casino : Page d'aide du casino")
async def ecohelp(message):
await message.channel.send("Eco+ help page \n"\
"?pinguncon : Ping the local dumbass\n"\
"?pingrand : Ping a random user\n"\
"?roulette : Play russian roulette\n"\
"?reload : Reset the russian roulette\n"\
"?casino_en : English help page for the casino")
async def hello(message):
await message.channel.send('henlo')
commentaires_zizi = [
#0
["Vous avez essayé de mesurer à la base ?","Dur d'avoir des chromosomes XX. Retourne à la cuisine"],\
#1
["J'ai pitié.", "Échec critique !"],\
#2
["Tu peux toujours te dire que la taille ne compte pas"],\
#3
["Dire que c'était ma taille à trois ans..."],\
#4
["Retourne dans ton 4x4 micropénis"],\
#5
["En impérial, ça aurait été la moyenne"],\
#6
["T'es pas la bite la plus dure du gloryhole"],\
#7
[""],\
#8
[""],\
#9
[""],\
#10
[""],\
#11
[""],\
#12
[""],\
#13
["La moyenne, pour de vrai"],\
#14
[""],\
#15
[""],\
#16
["La verité est dure à avaler"],\
#17
["C'est roc, c'est un pic, c'est un cap. Que dis-je ? C'est une péninsule"],\
#18
["Si le goût se rapporte à la taille, vous êtes le phoenix des hôtes du gang bang"],\
#19
["Bien membré !"],\
#20
["Je veux la même !", "Coup critique !"],\
#21
["Profite de tes chromosomes YY :moai:", "La taille moyenne en Uganda"]
]
async def zizi(message):
id = message.author.id
size = random.randint(0,10) + random.randint(0,11)
comment = random.choice(commentaires_zizi[size])
await message.channel.send(f"<@{id}>, votre chibre fait **{size} cm**. {comment}")
@client.event
async def on_ready():
print(f'We have logged in as {client.user}')
async for guild in client.fetch_guilds(limit=150):
print(str(guild.id)+":")
guilds.append(guild)
sid = str(guild.id)
globals()["gmembers"] |= {sid:[]}
async for member in guild.fetch_members(limit=150):
globals()["gmembers"][sid].append(member)
print(" "+str(member))
cmd_dict = {\
"?hello":hello,\
"?pinguncon":pinguncon,\
"?pingrand":pingrand,\
"?pingunjuif":pingjuif,\
"?zizi":zizi,\
"?roulette":roulette,\
"?help":ecohelp,\
"?aide":ecoaide,\
"?init":casino_init,\
"?cash":balance,\
"?collect":collect,\
"?lb":leaderboard,\
"?reload":reload,\
"?slot":slot,\
"?roll":roll,\
"?transfer":transfer,\
"?casino":casino_aide,\
"?course":course,\
"?bet":bet,\
}
@client.event
async def on_message(message):
if message.author == client.user:
return
content = message.content.split(" ")[0]
if not content:
return
if content[0] != "?":
return
if not content in cmd_dict:
await message.reply("Commande non reconnue !")
return
try:
await cmd_dict[content](message)
except Exception as err:
print(err)
await message.reply("Une erreur s'est produite : `" + str(err) + "`")
def do_forgejo_thread():
forgejo.app.run(port=5000)
forgejo_thread = threading.Thread()
forgejo_thread.run = do_forgejo_thread
print("227")
forgejo_thread.start()
client.run(token)