Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Small fixes and additions #4

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions Cogs/Json/cdb.json
Original file line number Diff line number Diff line change
@@ -1,4 +1,14 @@
{
"members": {
"1119308131932049459": {
"open": 1,
"date": "2023-09-05 03:46:08.686633",
"id": 1119308131932049459
},
"1137319866693599282": {
"open": 1,
"date": "2023-09-05 03:49:56.857832",
"id": 1137319866693599282
}
}
}
128 changes: 105 additions & 23 deletions Cogs/app.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@

import discord
import json
import random
Expand All @@ -11,6 +12,24 @@
import Email.fetchmail as fetch
import Cogs.Json.jshelper as jshelper
from discord.ext.commands.cooldowns import BucketType
import logging
import string
from hashlib import sha256 as hsh
from pathlib import Path

upper_chars = string.ascii_uppercase
lower_chars = string.ascii_lowercase
nums = string.digits
special_chars = string.punctuation


logger = logging.getLogger(__name__)
logger.setLevel(logging.CRITICAL)
log_formatter = logging.Formatter('%(levelname)s: %(asctime)s - %(message)s')
log_file_handler = logging.FileHandler(filename=f'{__name__}.log',mode='a')
log_file_handler.setFormatter(log_formatter)
logger.addHandler(log_file_handler)


t = BucketType.user
rate = 1
Expand Down Expand Up @@ -90,27 +109,79 @@ async def setrole(self, ctx, role: discord.Role):
embed = discord.Embed(title=f"{role} has been set as the role.", color=0xf50000)
await ctx.send(embed=embed)


async def make_token(self,member):
try:
t = datetime.now()
logger.debug(f"make_token: t = {t}")
token_string = f"{member.id}-{t}"
logger.debug(f"make_token: token_string = {token_string}")
transaction_token = hsh(token_string.encode('utf-8')).hexdigest()[:50]
logger.debug(f"make_token: token = {transaction_token}")
token_dir = Path('token_files')
token_file = Path(token_dir, "tokens.json")
token_dir.mkdir(parents=True, exist_ok=True)
logger.debug(f"make_token: tokens_dir created.")
if not token_file.is_file():
with open(token_file, 'w') as f:
f.write("{}")
logger.debug(f"make_token: token file created.")

with open(token_file, 'r') as f:
logger.debug(f"make_token: token file open")
tokens = json.load(f)

info = {transaction_token:member.name}
tokens.update(info)
with open(token_file, 'w') as f:
json.dump(tokens,f, indent=6)
await member.send("Below is your Transaciton ID")
await member.send(transaction_token)
logger.debug(f"make_token: token sent to user.")
except Exception as e:
logger.critical(f"There was an error generating and sending the transaction ID. The exception is below.\n\n{e}")

@commands.command(pass_context=True, name="who")
@commands.has_permissions(administrator=True)
async def who(self,ctx,*,transaction_id):
await ctx.message.delete()
tokens_dir = Path("token_files")
token_file = Path(tokens_dir,'tokens.json')
try:
with open(token_file,'r') as f:
tokens = json.load(f)
name = tokens.get(transaction_id)
await ctx.send(name)
except Exception as e:
await ctx.send("Sorry something went wrong.")
logger.debug(f"There was an issue with who. The exception traceback is below.\n\n{e}\n\n")


@commands.command()
@commands.has_permissions(administrator=True)
async def setpayment(self, ctx, type, addy):
type = str.lower(type)
if type == "cashapp":
data = jshelper.openf("/config/config.json")
data["cashapp"] = str(addy)
self.ca = f'Cashapp: ${str(addy)}'
jshelper.savef("/config/config.json", data)
embed = discord.Embed(title=f"${addy} has been set as the cashapp address.", color=0xf50000)
await ctx.send(embed=embed)
elif type == "venmo":
data = jshelper.openf("/config/config.json")
data["venmo"] = str(addy)
self.vm = f'Venmo: ${str(addy)}'
jshelper.savef("/config/config.json", data)
embed = discord.Embed(title=f"@{addy} has been set as the Venmo address.", color=0xf50000)
await ctx.send(embed=embed)
else:
embed = discord.Embed(title=f'Error, Please use ".setpayment (cashapp/venmo) address"', color=0xf50000)
await ctx.send(embed=embed)
try:
type = str.lower(type)
if type == "cashapp":
data = jshelper.openf("/config/config.json")
data["cashapp"] = str(addy)
self.ca = f'Cashapp: ${str(addy)}'
jshelper.savef("/config/config.json", data)
embed = discord.Embed(title=f"${addy} has been set as the cashapp address.", color=0xf50000)
await ctx.send(embed=embed)
elif type == "venmo":
data = jshelper.openf("/config/config.json")
data["venmo"] = str(addy)
self.vm = f'Venmo: ${str(addy)}'
jshelper.savef("/config/config.json", data)
embed = discord.Embed(title=f"@{addy} has been set as the Venmo address.", color=0xf50000)
await ctx.send(embed=embed)
else:
embed = discord.Embed(title=f'Error, Please use ".setpayment (cashapp/venmo) address"', color=0xf50000)
await ctx.send(embed=embed)

except Exception as e:
logger.critical(f'Set Payment Failed! The exception is below. \n\n{e}')

async def assignrole(self, ctx, role):
role = get(ctx.guild.roles, name=role)
Expand All @@ -127,7 +198,9 @@ async def cancel(self, ctx):
@commands.cooldown(rate, per, t)
@commands.command(ignore_extra=False)
async def donate(self, ctx):
await ctx.message.delete()
await ctx.channel.send(f'{ctx.author.mention} Please check dms!')

one = '1️⃣'
two = '2️⃣'
nay = '❌'
Expand Down Expand Up @@ -159,6 +232,7 @@ def check(reaction, user):
else:
if str(reaction.emoji) == one:
payment = self.ca
qr = f"https://cash.app/qr/{payment}?size=288&margin=0"
elif str(reaction.emoji) == two:
payment = self.vm
else:
Expand All @@ -170,11 +244,19 @@ def check(reaction, user):
jshelper.makeopen(ctx.author.id)

embed = discord.Embed(title=f'Payment via {payment}',color=0xf50000)
embed.add_field(name=f"Price: ${price} \n{payment}\nNote: {note}\nMake sure you send the exact amount with the NOTE.",
value=f"This page will timeout in 30 mins.\nClick {tick} once you have sent the payment.")
# embed.add_field(name=f"Price: ${price} \n{payment}\nNote: {note}\nMake sure you send the exact amount with the NOTE.",
# value=f"This page will timeout in 30 mins.\nClick {tick} once you have sent the payment.")
embed.add_field(
name=f"Price: ${price} \n{payment}\nNote: Your Transaction ID \nMake sure you send the exact amount with the Transaction ID in the NOTE or For field.",
value=f"This page will timeout in 30 mins.\nClick {tick} once you have sent the payment.")
msg = await ctx.author.send(embed=embed)
await ctx.author.send(note)
# await ctx.author.send("Here is an example of how to fill out the cashapp form.", file=discord.File('Screenshots/example_cashapp.jpg'))
await ctx.author.send("Below is the note so you can copy and paste:")
# await ctx.author.send(f"Note: {note}\n\n")
await self.make_token(ctx.author)
await ctx.author.send(f"https://cash.app/{payment.split(': ')[-1]}")
await msg.add_reaction(tick)

try:
reaction, ctx.author = await self.bot.wait_for('reaction_add', timeout=1800.0, check=check)
except asyncio.TimeoutError:
Expand All @@ -200,5 +282,5 @@ async def fetch_email(self):
fetch.fetchmail()


def setup(bot):
bot.add_cog(app(bot))
async def setup(bot):
await bot.add_cog(app(bot))
15 changes: 12 additions & 3 deletions Email/db.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
import sqlite3
import os
import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.CRITICAL)
log_formatter = logging.Formatter('%(levelname)s: %(asctime)s - %(message)s')
log_file_handler = logging.FileHandler(filename=f'{__name__}.log',mode='a')
log_file_handler.setFormatter(log_formatter)
logger.addHandler(log_file_handler)


DB_URL = os.getcwd() + '/Email/payrecs.db'

Expand All @@ -8,9 +17,9 @@ def create_connection(db_file):
conn = None
try:
conn = sqlite3.connect(db_file)
print("Connected to db")
except Error as e:
print("error in connecting to db")
logger.debug('Connected to db')
except Exception as e:
logger.error(f'There was an error connecting to the database below is the exception: \n\n {e}\n\n__________________________________')
finally:
if conn:
return conn
Expand Down
9 changes: 8 additions & 1 deletion Email/fetchmail.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,14 @@
import json
import os
import Cogs.Json.jshelper as jshelper
import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.CRITICAL)
log_formatter = logging.Formatter('%(levelname)s: %(asctime)s - %(message)s')
log_file_handler = logging.FileHandler(filename=f'{__name__}.log',mode='a')
log_file_handler.setFormatter(log_formatter)
logger.addHandler(log_file_handler)

def fetchmail():
try:
Expand Down Expand Up @@ -52,4 +59,4 @@ def fetchmail():
mail.close()
mail.logout()
except Exception as e:
print(e)
logger.debug(e)
36 changes: 25 additions & 11 deletions Run.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,46 +6,54 @@
import json
import Cogs.Json.jshelper as jshelper
import sys
import logging

logger = logging.getLogger(__name__)
logger.setLevel(logging.CRITICAL)
log_formatter = logging.Formatter('%(levelname)s: %(asctime)s - %(message)s')
log_file_handler = logging.FileHandler(filename=f'{__name__}.log',mode='a')
log_file_handler.setFormatter(log_formatter)
logger.addHandler(log_file_handler)

jshelper.prestart()
data = jshelper.openf("/config/config.json")
if data["token"] == "":
print("Missing Config.")
logger.critical('Missing Config')
sys.exit()

data = jshelper.openf("/config/config.json")
TOKEN = data["token"]
intents = discord.Intents.default()
intents = discord.Intents.all()
intents.members = True
bot = commands.Bot(command_prefix=".", intents = intents)
bot.remove_command('help')


@bot.event
async def on_ready():
print("bot is online.")
logger.debug('Bot Online')


@bot.command()
@commands.has_permissions(administrator=True)
async def load(ctx, name):
bot.load_extension(f'Cogs.{name}')
print(f"The {name} cog has been loaded successfully.")
logger.debug(f"The {name} cog has been loaded successfully.")


@bot.command()
@commands.has_permissions(administrator=True)
async def unload(ctx, name):
bot.unload_extension(f'Cogs.{name}')
print(f"The {name} cog has been unloaded successfully.")
logger.debug(f"The {name} cog has been unloaded successfully.")


@bot.command()
@commands.has_permissions(administrator=True)
async def reload(ctx, name):
bot.unload_extension(f'Cogs.{name}')
bot.load_extension(f'Cogs.{name}')
print(f"The {name} cog has been reloaded successfully.")
logger.debug(f"The {name} cog has been reloaded successfully.")


@bot.event
Expand All @@ -65,11 +73,17 @@ async def all(ctx):
for filename in os.listdir("Cogs"):
if filename.endswith('.py'):
bot.load_extension(f'Cogs.{filename[:-3]}')
print("All cogs has been reloaded.")
logger.debug("All cogs has been reloaded.")


for filename in os.listdir("Cogs"):
if filename.endswith('.py'):
bot.load_extension(f'Cogs.{filename[:-3]}')
async def load_cogs():
try:
logger.debug('Loading cogs')
await bot.load_extension('Cogs.app')
logger.debug('App Cog loaded')
except Exception as e:
logger.critical(f'There was an error loading the cogs. Below is the exception: \n\n {e} \n\n________________________')

bot.run(TOKEN)
if __name__ == "__main__":
asyncio.run(load_cogs())
bot.run(TOKEN)
Binary file added Screenshots/example_cashapp.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
17 changes: 9 additions & 8 deletions config/config.json
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@

{
"token": "",
"role": "",
"token": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"role": "donator",
"Price": 10,
"cashapp": "",
"venmo": "",
"cashapp": "test",
"venmo": "test",
"note":"1a001-",
"user":"",
"password":"",
"imap_url":""
}
"user":"[email protected]",
"password":"vaadsgagcqlgzsox",
"imap_url":"imap.gmail.com"
}