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

dev1 up to date with master #59

Merged
merged 17 commits into from
Jun 9, 2021
Merged
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
31 changes: 31 additions & 0 deletions .github/workflows/notifications.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
# This is a basic workflow to help you get started with Actions

name: Notification system

# Controls when the action will run.
on:
# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:

# A workflow run is made up of one or more jobs that can run sequentially or in parallel
jobs:
build:
# The type of runner that the job will run on
runs-on: ubuntu-latest

# Steps represent a sequence of tasks that will be executed as part of the job
steps:
# Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
- uses: actions/checkout@v2

# Runs a single command using the runners shell
- name: executing remote ssh commands using key
uses: appleboy/ssh-action@master
with:
host: ${{ secrets.HOST }}
username: ${{ secrets.USERNAME }}
key: ${{ secrets.KEY }}
port: ${{ secrets.PORT }}
script: |
cd ~/CoraBot/webhook
python3 updateBroadcaster.py
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -122,6 +122,7 @@ modules/test_module.py

#Log
Coralog.txt
broadcaster_log.txt

#Database
Databases/
Expand Down
16 changes: 16 additions & 0 deletions Other scripts/DBdebug.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
# This script is used to alter the database during development so that alterations to things like tables can be made easily.


import sqlite3

with sqlite3.connect("Databases/database.db") as conn:
c = conn.cursor()
c.execute(
"""ALTER TABLE RolePolls_Votes
ADD COLUMN Timestamp TEXT;"""
)
c.execute(
"""ALTER TABLE RolePolls
ADD COLUMN Timestamp TEXT;"""
)
conn.commit()
30 changes: 30 additions & 0 deletions Other scripts/dbviewer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import sqlite3

def main():
with sqlite3.connect("Databases/database.db") as conn:
c = conn.cursor()

table = input("Table to search from: ")
whereToSearch = input("Search paramiters: ")
toFile = input("Print output to file? Y/N: ").upper()

SQL_clause = f"SELECT * FROM {table.strip()}"
if whereToSearch.strip() != "":
SQL_clause += f" WHERE {whereToSearch.strip()}"

c.execute(SQL_clause)
result = c.fetchall()

if toFile.strip() == "Y":
with open("result.txt", "w", encoding="utf-8") as fi:
for r in result:
for t in r:
fi.write(str(t) + ";")
fi.write("\n")

else:
for r in result:
print(r)


main()
4 changes: 1 addition & 3 deletions constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,6 @@ def get_tokens():

# Functional constants
PREFIX = "!c "
AUTHOR = "This bot is maintained by Appelsiini1"
GIT = "Source code for this bot can be found at https://github.com/Appelsiini1/CoraBot"
DB_F = os.path.join(
os.path.dirname(os.path.realpath(__file__)), "Databases", "database.db"
)
Expand Down Expand Up @@ -78,4 +76,4 @@ def __start__(self):


# Version number
VERSION = "v1.14.7"
VERSION = "v1.14.11"
21 changes: 15 additions & 6 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,12 +104,21 @@ async def on_message(message):
await message.channel.send("Hello!")
elif cmd == "help":
await commands.cmds(message)
elif cmd == "author":
await message.channel.send(AUTHOR)
elif cmd == "git":
await message.channel.send(GIT)
elif cmd == "version":
await message.channel.send(f"CoraBot `{VERSION}`")
elif cmd in ["author", "git", "version"]:
await message.channel.send("This command has been depricated and will be removed soon. Use `!c info` instead.")
elif cmd == "info":
emb = discord.Embed()
emb.title = "CoraBot Info"
emb.description = f"**Created by** Appelsiini1\nThe source code & development info for this bot can be found at https://github.com/Appelsiini1/CoraBot\n\nVersion: {VERSION}"
emb.color = common.get_hex_colour(cora_blonde=True)
emb.set_thumbnail(
url="https://media.discordapp.net/attachments/693166291468681227/834200862246043648/cora_pfp.png"
)

try:
await message.channel.send(embed=emb)
except discord.errors.Forbidden:
common.forbiddenErrorHandler(message)
elif cmd == "inspire":
await quote.get_quote(message)
elif cmd == "insult":
Expand Down
4 changes: 1 addition & 3 deletions modules/commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,7 @@
async def cmds(message):
cmd_list = """`hi` (alias: `hello`)
`help`
`author`
`git`
`version`
`info`
`inspire`
`insult [user]`
`f` (alias: `F`)
Expand Down
10 changes: 10 additions & 0 deletions modules/common.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,7 @@ def initializeDatabase():
Author_ID INT,
Options TEXT,
PollName TEXT,
Timestamp TEXT,
PRIMARY KEY (Poll_ID)
);"""
)
Expand All @@ -112,6 +113,7 @@ def initializeDatabase():
Poll_ID INT,
Voter_ID INT,
Votes TXT,
Timestamp TEXT,
PRIMARY KEY (Vote_ID)
FOREIGN KEY (Poll_ID) REFERENCES RolePolls(Poll_ID)
ON DELETE CASCADE
Expand Down Expand Up @@ -162,6 +164,14 @@ def initializeDatabase():
);"""
)


# ID table
c.execute("""CREATE TABLE IF NOT EXISTS IDs(
ID INT,
Type TEXT,
PRIMARY KEY (ID)
);""")

# Current auctions
c.execute(
"""CREATE TABLE IF NOT EXISTS Auctions(
Expand Down
21 changes: 17 additions & 4 deletions modules/poll.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import logging
import sqlite3
import re
import datetime

from modules.common import get_hex_colour, selectReactionEmoji
from modules.emoji_list import _EMOJIS
Expand Down Expand Up @@ -264,6 +265,7 @@ async def endPolls(message):
if polls != 0:
for poll_id in polls:
c.execute(f"DELETE FROM RolePolls WHERE Poll_ID={poll_id}")
c.execute(f"DELETE FROM RolePolls_Votes WHERE Poll_ID={poll_id}")
conn.commit()
success = 1
else:
Expand Down Expand Up @@ -293,6 +295,7 @@ async def endPolls(message):
if polls != 0:
for poll_id in polls:
c.execute(f"DELETE FROM RolePolls WHERE Poll_ID={poll_id}")
c.execute(f"DELETE FROM RolePolls_Votes WHERE Poll_ID={poll_id}")
conn.commit()
success = 1
else:
Expand Down Expand Up @@ -328,6 +331,7 @@ async def endPolls(message):
if polls != 0:
for poll_id in polls:
c.execute(f"DELETE FROM RolePolls WHERE Poll_ID={poll_id}")
c.execute(f"DELETE FROM RolePolls_Votes WHERE Poll_ID={poll_id}")
conn.commit()
success = 1
else:
Expand All @@ -354,6 +358,7 @@ async def endPolls(message):
if polls != 0:
for poll_id in polls:
c.execute(f"DELETE FROM RolePolls WHERE Poll_ID={poll_id}")
c.execute(f"DELETE FROM RolePolls_Votes WHERE Poll_ID={poll_id}")
conn.commit()
success = 1
else:
Expand All @@ -363,6 +368,8 @@ async def endPolls(message):
await message.delete()
except Exception as e:
logging.exception("Poll ending command message deletion failed.")
else:
logging.error("Something went wrong when ending the poll.")


# ######################################################################################################## #
Expand Down Expand Up @@ -569,9 +576,9 @@ async def startRolePoll(message):
title = f"A poll by {message.author.name}"
titleStatus = 1

c.execute("SELECT Poll_ID FROM RolePolls ORDER BY Poll_ID DESC")
c.execute("SELECT ID FROM IDs WHERE Type='RolePoll' ORDER BY ID DESC")
prevPollID = c.fetchone()
poll_id = 100 if prevPollID == None else prevPollID[0] + 1
poll_id = 103 if prevPollID == None else prevPollID[0] + 1

if len(args) <= 1 or message.content.find(";") == -1:
# help command
Expand Down Expand Up @@ -611,20 +618,24 @@ async def startRolePoll(message):
if titleStatus == 1:
title = None

timestamp = datetime.datetime.today().strftime("%d.%m.%Y %H:%M %Z%z")

success = 0
for i in range(5):
try:
c.execute(
"INSERT INTO RolePolls VALUES (?,?,?,?,?,?)",
"INSERT INTO RolePolls VALUES (?,?,?,?,?,?,?)",
(
poll_id,
message.channel.id,
message.guild.id,
message.author.id,
option_str,
title,
timestamp,
),
)
c.execute("INSERT INTO IDs VALUES (?,?)", (poll_id, "RolePoll"))
success = 1
break
except sqlite3.IntegrityError:
Expand Down Expand Up @@ -770,4 +781,6 @@ async def rolePollEndHelper(message, c, poll=None, polls=None):
emb.color = get_hex_colour(cora_eye=True)
await message.channel.send(embed=emb)
return poll_ids
return 0
else:
logging.error("This should not be going here in RolePoll end helper, wtf?")
return 0
2 changes: 1 addition & 1 deletion modules/vaccine.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ def makeEmbed(one_dose, two_doses, emb, areaCode="Finland"):
emb.title = f"Current number of COVID-19 vaccinated people in {area}:"
emb.description = f"One dose: {one_dose}\nTwo doses: {two_doses}"
emb.color = get_hex_colour(cora_eye=True)
emb.set_footer(text=f"Source: THL.fi")
emb.set_footer(text=f"Source: Finnish Institute for Health and Welfare (THL.fi)")
return emb


Expand Down
7 changes: 5 additions & 2 deletions modules/vote.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import discord
import sqlite3
import logging
import datetime

from modules.common import get_hex_colour
from constants import DB_F
Expand Down Expand Up @@ -142,12 +143,14 @@ async def vote(message):
db_id = c.fetchone()
maxid = 1 if db_id == None else db_id[0]

timestamp = datetime.datetime.today().strftime("%d.%m.%Y %H:%M %Z%z")

success = 0
for i in range(5):
try:
c.execute(
"INSERT INTO RolePolls_Votes VALUES (?,?,?,?)",
(maxid + 1, poll_id, message.author.id, vote_str),
"INSERT INTO RolePolls_Votes VALUES (?,?,?,?,?)",
(maxid + 1, poll_id, message.author.id, vote_str, timestamp),
)
success = 1
break
Expand Down
53 changes: 53 additions & 0 deletions webhook/updateBroadcaster.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import requests
import logging


def main():
logging.basicConfig(
filename="broadcaster_log.txt",
level=logging.INFO,
format="%(asctime)s %(levelname)s - %(message)s",
datefmt="%d/%m/%Y %H:%M:%S",
)

with open("urls.txt", "r") as f:
urls = f.readlines()

with open("versions.txt", "r") as f:
txtFromFile = f.readline()
if txtFromFile.startswith("v"):
title = f"New version of CoraBot is live!"
version = txtFromFile
txtFromFile = f.readline()

text = f"**{version}**\n"
while txtFromFile.strip() != "###":
text += txtFromFile
txtFromFile = f.readline()

# for all params, see https://discordapp.com/developers/docs/resources/webhook#execute-webhook
data = {
"username": "CoraBot Updates",
"avatar_url": "https://media.discordapp.net/attachments/693166291468681227/851120811393417216/cora_pfp_update_pride.png",
}

# for all params, see https://discordapp.com/developers/docs/resources/channel#embed-object
data["embeds"] = [{"description": text, "title": title}]

for i, url in enumerate(urls):
if url.strip() == "":
continue
result = requests.post(url.strip(), json=data)

try:
result.raise_for_status()
except requests.exceptions.HTTPError:
logging.exception("Error occured while sending message:")
else:
logging.info(
f"Payload {i} delivered successfully, code {result.status_code}."
)


if __name__ == "__main__":
main()
3 changes: 3 additions & 0 deletions webhook/versions.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
v1.14.11
- Fix advanced polls not ending correctly
###