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

Update Github Action #10

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

name: Code Quailty and Linter

# Controls when the workflow will run
on:
# Triggers the workflow on push or pull request events but only for the main branch
push:
branches: [ main ]
# Triggers the workflow on pull request events
pull_request:
branches: [ main ]
branches:
- '**'

# A workflow run is made up of one or more jobs that can run sequentially or in parallel
jobs:
# This workflow contains a single job called "build"
build:
# The type of runner that the job will run on
run-linters:
name: Run linters
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@v1
- uses: ricardochaves/[email protected]
- name: Check out Git repository
uses: actions/checkout@v2

- name: Set up Python
uses: actions/setup-python@v1
with:
python-version: 3.x

- name: Install Python dependencies
run: pip install black flake8

- name: Run linters
uses: wearerequired/lint-action@v1
with:
python-root-list: "python_alelo tests"
use-pylint: false
use-pycodestyle: false
use-flake8: false
use-black: false
use-mypy: false
use-isort: false
extra-pylint-options: ""
extra-pycodestyle-options: ""
extra-flake8-options: ""
extra-black-options: ""
extra-mypy-options: ""
extra-isort-options: ""
black: true
flake8: true
black_args: "--line-length=79"
flake8_args: "--max-line-length=79 --ignore=E203,E266,E501,W503 --select=B,C,E,F,W,T4,B9"
auto_fix: true
76 changes: 47 additions & 29 deletions bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,86 +5,104 @@

# For get_current_time
from urllib import request, error
from datetime import datetime, timedelta
from datetime import datetime, timedelta

load_dotenv()
TOKEN = os.getenv('DISCORD_TOKEN')
TOKEN = os.getenv("DISCORD_TOKEN")

bot = commands.Bot(command_prefix='!')
bot = commands.Bot(command_prefix="!")
user_dict = {}


def get_current_time():
str_time = request.urlopen('https://www.naver.com').headers['Date']
current_time = datetime.strptime(str_time,'%a, %d %b %Y %H:%M:%S %Z') - timedelta(hours=-9)
str_time = request.urlopen("https://www.naver.com").headers["Date"]
current_time = datetime.strptime(
str_time, "%a, %d %b %Y %H:%M:%S %Z"
) - timedelta(hours=-9)
return current_time.strftime("%Y-%m-%d %H:%M:%S")


def calculate_elpased(start_time, end_time):
start_time = datetime.strptime(start_time, "%Y-%m-%d %H:%M:%S")
end_time = datetime.strptime(end_time, "%Y-%m-%d %H:%M:%S")

return end_time - start_time


def handle_timedelta(td):
days = td.days
hours = td.seconds//3600
minutes = (td.seconds//60)%60
hours = td.seconds // 3600
minutes = (td.seconds // 60) % 60
seconds = td.seconds % 60
return_string = ''
return_string = ""
if days != 0:
return_string += f'{days}일 '
return_string += f"{days}일 "
if hours != 0:
return_string += f'{hours}시간 '
return_string += f"{hours}시간 "
if minutes != 0:
return_string += f'{minutes}분 '
return_string += f"{minutes}분 "
if seconds != 0:
return_string += f'{seconds}초'
return_string += f"{seconds}초"

return return_string


@bot.event
async def on_ready():
print(f'{bot.user.name} has connected to Discord!')
print(f"{bot.user.name} has connected to Discord!")


@bot.command(name='hi')
@bot.command(name="hi")
async def hi(ctx):
user_name = ctx.author.name
current_time = get_current_time()

if user_name not in user_dict:
user_dict[user_name] = {"start_time":None, "count":0, "elapsed_time":timedelta(0)}
user_dict[user_name] = {
"start_time": None,
"count": 0,
"elapsed_time": timedelta(0),
}
user_dict[user_name]["start_time"] = current_time

send_message = f'안녕하세요 {user_name}님! : {current_time}'
send_message = f"안녕하세요 {user_name}님! : {current_time}"
await ctx.send(send_message)

@bot.command(name='bye')


@bot.command(name="bye")
async def bye(ctx):
user_name = ctx.author.name
current_time = get_current_time()

if user_name in user_dict:
if user_dict[user_name]["start_time"] is not None:
user_dict[user_name]["elapsed_time"] += calculate_elpased(user_dict[user_name]["start_time"],
current_time)
user_dict[user_name]["elapsed_time"] += calculate_elpased(
user_dict[user_name]["start_time"], current_time
)
user_dict[user_name]["count"] += 1
user_dict[user_name]["start_time"] = None

send_message = f'수고하셨습니다 {user_name}님! : {current_time}'
send_message = f"수고하셨습니다 {user_name}님! : {current_time}"
await ctx.send(send_message)

@bot.command(name='list')

@bot.command(name="list")
async def listing_results(ctx):
send_message = '총 공부 시간 리스트 (정렬X)\n'
send_message = "총 공부 시간 리스트 (정렬X)\n"
for user_name, study_record in user_dict.items():
elapsed_time = handle_timedelta(study_record["elapsed_time"])
send_message += f'{user_name} : 총 시간 {elapsed_time}, {study_record["count"]}회 진행\n'

send_message += (
f'{user_name} : 총 시간 {elapsed_time}, {study_record["count"]}회 진행\n'
)

await ctx.send(send_message)


@bot.event
async def on_error(event, *args, **kwargs):
with open('err.log', 'a') as f:
if event == 'on_message':
f.write(f'Unhandled message: {args[0]}\n')
with open("err.log", "a") as f:
if event == "on_message":
f.write(f"Unhandled message: {args[0]}\n")


bot.run(TOKEN)
41 changes: 24 additions & 17 deletions main.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,36 +7,41 @@
from utils.handle_time import *

load_dotenv()
token = os.getenv('DISCORD_TOKEN')
db_name = os.getenv('DISCORD_DB')
tb_name = os.getenv('DISCORD_DB_TB')
admin_name = os.getenv('DISCORD_ADMIN')
token = os.getenv("DISCORD_TOKEN")
db_name = os.getenv("DISCORD_DB")
tb_name = os.getenv("DISCORD_DB_TB")
admin_name = os.getenv("DISCORD_ADMIN")

bot = commands.Bot(command_prefix="!")

bot = commands.Bot(command_prefix='!')

@bot.event
async def on_ready():
init_db(db_name, tb_name)
print(f'{bot.user.name} has connected to Discord!')
print(f"{bot.user.name} has connected to Discord!")


@bot.command(name='hi')
@bot.command(name="hi")
async def hi(ctx):
current_time = get_current_time()
start_study(ctx.author.name, tb_name, current_time)
await ctx.send(f'{current_time} : 안녕하세요 {ctx.author.name}님!')

@bot.command(name='bye')
await ctx.send(f"{current_time} : 안녕하세요 {ctx.author.name}님!")


@bot.command(name="bye")
async def bye(ctx):
current_time = get_current_time()
end_study(ctx.author.name, tb_name, current_time)
await ctx.send(f'{current_time} :안녕히가세요 {ctx.author.name}님!')
await ctx.send(f"{current_time} :안녕히가세요 {ctx.author.name}님!")

@bot.command(name='list')

@bot.command(name="list")
async def listing(ctx):
list_all_from_db = list_study(tb_name)
await ctx.send(list_all_from_db)

@bot.command(name='exit')

@bot.command(name="exit")
async def exitBot(ctx):
if ctx.author.name == admin_name:
close_db()
Expand All @@ -45,12 +50,14 @@ async def exitBot(ctx):
else:
await ctx.send("Admin만 이 명령어를 사용할 수 있습니다.")


@bot.event
async def on_error(event, *args, **kwargs):
with open('err.log', 'a') as f:
if event == 'on_message':
f.write(f'Unhandled message: {args[0]}\n')
with open("err.log", "a") as f:
if event == "on_message":
f.write(f"Unhandled message: {args[0]}\n")
else:
raise

bot.run(token)

bot.run(token)
30 changes: 23 additions & 7 deletions utils/handle_db.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,31 +4,37 @@
conn = None
COLUMNS = "USER_NM, STD_AMT, STD_CNT, LAST_LOGIN_HMS, LAST_OUT_HMS"


def init_db(db_name, table_name):
global conn
conn = sqlite3.connect(db_name)
c = conn.cursor()
c.execute(f"SELECT COUNT(*) FROM sqlite_master WHERE name='{table_name}';")

if c.fetchone()[0] == 0:
c.execute(f"CREATE TABLE {table_name}(USER_NM text, STD_AMT int, STD_CNT int, LAST_LOGIN_HMS timestamp, LAST_OUT_HMS timestamp);")
c.execute(
f"CREATE TABLE {table_name}(USER_NM text, STD_AMT int, STD_CNT int, LAST_LOGIN_HMS timestamp, LAST_OUT_HMS timestamp);"
)
conn.commit()


def start_study(user_name, table_name, current_time):
global conn
print(f"start study : {current_time}")
query = None
datas = None

c = conn.cursor()
c.execute(f"SELECT * FROM {table_name} WHERE USER_NM = ?", (user_name, ))
c.execute(f"SELECT * FROM {table_name} WHERE USER_NM = ?", (user_name,))
rows = c.fetchall()
if len(rows) == 0:
query = f"INSERT INTO {table_name}({COLUMNS}) VALUES (?, ?, ?, ?, ?)"
datas = [user_name, 0, 0, current_time, "NULL"]
print(f"New User : {user_name}")
else:
c.execute(f"SELECT * FROM {table_name} WHERE USER_NM = ?", (user_name, ))
c.execute(
f"SELECT * FROM {table_name} WHERE USER_NM = ?", (user_name,)
)
query = f"UPDATE {table_name} SET LAST_LOGIN_HMS = ? WHERE USER_NM = ?"
datas = [current_time, user_name]

Expand All @@ -37,6 +43,7 @@ def start_study(user_name, table_name, current_time):

return None


def end_study(user_name, table_name, current_time):
global conn
print(f"end study : {current_time}")
Expand All @@ -46,20 +53,27 @@ def end_study(user_name, table_name, current_time):
c = conn.cursor()
c.execute(f"SELECT * FROM {table_name} WHERE USER_NM=?", (user_name,))
rows = c.fetchall()[0]

if len(rows) == 0:
print(f"New User : {user_name}")
return -1

start_time = rows[3]
elapsed_time = calculate_elapsed(start_time, current_time).total_seconds()
datas = (rows[1]+elapsed_time, rows[2]+1, "NULL", current_time, user_name)
datas = (
rows[1] + elapsed_time,
rows[2] + 1,
"NULL",
current_time,
user_name,
)

c.execute(query, datas)
conn.commit()

return None


def list_study(table_name):
global conn
c = conn.cursor()
Expand All @@ -71,11 +85,13 @@ def list_study(table_name):
results += str(row) + "\n"
return results


def close_db():
global conn
conn.close()

return None


def edit_time(user_name, edit_type):
return None
return None
Loading