Skip to content

Commit

Permalink
Merge pull request #2 from v-ut-d/dockerize
Browse files Browse the repository at this point in the history
Dockerize
  • Loading branch information
phenylshima authored Sep 19, 2022
2 parents ccad4f0 + b684dc9 commit 04f18f4
Show file tree
Hide file tree
Showing 10 changed files with 194 additions and 60 deletions.
88 changes: 88 additions & 0 deletions .github/workflows/docker-publish.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
name: Docker

# This workflow uses actions that are not certified by GitHub.
# They are provided by a third-party and are governed by
# separate terms of service, privacy policy, and support
# documentation.

on:
push:
# Publish semver tags as releases.
tags: [ 'v*.*.*' ]

env:
# Use docker.io for Docker Hub if empty
REGISTRY: ghcr.io
# github.repository as <account>/<repo>
IMAGE_NAME: ${{ github.repository }}


jobs:
build:

runs-on: ubuntu-latest
permissions:
contents: read
packages: write
# This is used to complete the identity challenge
# with sigstore/fulcio when running outside of PRs.
id-token: write

steps:
- name: Checkout repository
uses: actions/checkout@v3

# Install the cosign tool except on PR
# https://github.com/sigstore/cosign-installer
- name: Install cosign
if: github.event_name != 'pull_request'
uses: sigstore/cosign-installer@7e0881f8fe90b25e305bbf0309761e9314607e25
with:
cosign-release: 'v1.9.0'


# Workaround: https://github.com/docker/build-push-action/issues/461
- name: Setup Docker buildx
uses: docker/setup-buildx-action@79abd3f86f79a9d68a23c75a09a9a85889262adf

# Login against a Docker registry except on PR
# https://github.com/docker/login-action
- name: Log into registry ${{ env.REGISTRY }}
if: github.event_name != 'pull_request'
uses: docker/login-action@28218f9b04b4f3f62068d7b6ce6ca5b26e35336c
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}

# Extract metadata (tags, labels) for Docker
# https://github.com/docker/metadata-action
- name: Extract Docker metadata
id: meta
uses: docker/metadata-action@98669ae865ea3cffbcbaa878cf57c20bbf1c6c38
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}

# Build and push Docker image with Buildx (don't push on PR)
# https://github.com/docker/build-push-action
- name: Build and push Docker image
id: build-and-push
uses: docker/build-push-action@ac9327eae2b366085ac7f6a2d02df8aa8ead720a
with:
context: .
push: ${{ github.event_name != 'pull_request' }}
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}

# Sign the resulting Docker image digest except on PRs.
# This will only write to the public Rekor transparency log when the Docker
# repository is public to avoid leaking data. If you would like to publish
# transparency data even for private images, pass --force to cosign below.
# https://github.com/sigstore/cosign
- name: Sign the published Docker image
if: ${{ github.event_name != 'pull_request' }}
env:
COSIGN_EXPERIMENTAL: "true"
# This step uses the identity token to provision an ephemeral certificate
# against the sigstore community Fulcio instance.
run: echo "${{ steps.meta.outputs.tags }}" | xargs -I {} cosign sign {}@${{ steps.build-and-push.outputs.digest }}
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
.env
__pycache__
__pycache__
data
108 changes: 60 additions & 48 deletions AtWaker.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,9 @@
import numpy as np
import os
from discord.ext import tasks, commands
from datetime import datetime, timedelta, date
# from dotenv import load_dotenv
from datetime import datetime, timedelta, date, timezone
import time
# import asyncio
import r
import pickle
import asyncio

# .envファイルの内容を読み込みます
# load_dotenv()
Expand Down Expand Up @@ -45,26 +42,31 @@
num_ra=0
min_display=10
auth=805067817271558184
conn=r.connect()

def cache_df(alias,df):
df_compressed = pickle.dumps(df)
res = conn.set(alias,df_compressed)
if res:
print('df cached')

def get_cached_df(alias):
data = conn.get(alias)
def cache_df(alias: str, df: pd.DataFrame | None):
name = alias.replace('/', '-')
if df is not None:
df.to_json(f'data/{name}.json', orient='table')


def get_cached_df(alias: str):
name = alias.replace('/', '-')
try:
return pickle.loads(data)
return pd.read_json(f'data/{name}.json', orient='table')
except:
print("No data")
return None


def load_vars():
global v
dbv=get_cached_df('variables_'+str(serverid))
v=get_cached_df('v_'+str(serverid))
v = get_cached_df('v_'+str(serverid))

dbv = get_cached_df('variables_'+str(serverid))
if dbv is None:
save_vars()
return

global emj
global contesting
global num_ra
Expand Down Expand Up @@ -150,7 +152,7 @@ async def contest_msg():
channel = bot.get_channel(channelid)
dt=(datetime.now()+timedelta(hours=9)).strftime('%Y-%m-%d')
msg=await channel.send(dt)
await msg.add_reaction(emoji=emj)
await msg.add_reaction(emj)
global msg_id
msg_id=msg.id
save_vars()
Expand Down Expand Up @@ -639,33 +641,39 @@ async def show_help(ctx):
await ctx.send(embed=embed)
return

@tasks.loop(seconds=60*interv)
async def loop():
# 現在の時刻
now=(time.time()+3600*9)%86400
print(now)
bool1l=(3600*hs+60*ms<=now<3600*hs+60*(ms+interv))
bool2l= not (serverid==None)
bool3l= not (channelid==None)
bool4l= (contesting==0)
dfd=get_cached_df('AtWaker_data_'+str(serverid))
dfr=get_cached_df('AtWaker_rate_'+str(serverid))
bool5l=isinstance(dfd, pd.DataFrame)
bool6l=isinstance(dfr, pd.DataFrame)
print(bool1l ,bool2l ,bool3l,bool4l,bool5l,bool6l)
if bool1l and bool2l and bool3l and bool4l and bool5l and bool6l:


tz_jst = timezone(timedelta(hours=9))


def create_time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, fold=0):
basetime = datetime(year=1970, month=1, day=1, tzinfo=tzinfo, fold=fold)
delta = timedelta(hours=hour, minutes=minute,
seconds=second, microseconds=microsecond)
return (basetime+delta).timetz()

@tasks.loop(time=create_time(hour=hs, minute=ms, tzinfo=tz_jst))
async def on_contest_start():
bool2l = not (serverid == None)
bool3l = not (channelid == None)
bool4l = (contesting == 0)
dfd = get_cached_df('AtWaker_data_'+str(serverid))
dfr = get_cached_df('AtWaker_rate_'+str(serverid))
bool5l = isinstance(dfd, pd.DataFrame)
bool6l = isinstance(dfr, pd.DataFrame)
if bool2l and bool3l and bool4l and bool5l and bool6l:
await contest()
elif(3600*hs+60*(ms+clen)<=now<3600*hs+60*(ms+interv+clen)) and (not bool4l):
dt=(datetime.now()+timedelta(hours=9)).strftime('%Y-%m-%d')

@tasks.loop(time=create_time(hour=hs, minute=ms+clen, tzinfo=tz_jst))
async def on_contest_end():
if contesting != 0:
dt = datetime.now(tz_jst).strftime('%Y-%m-%d')
await contest_end(dt)
elif(3600*hgn+60*mgn-300*interv<=now<3600*hgn+60*mgn-240*interv):
channel = bot.get_channel(channelid)
await channel.send('みんな寝る時間ですよ!おやすみー!また明日!')
# else:
# for i in range(1,msg_raz):
# if (3600*hs+60*(ms+clen*i/msg_raz)<=now<3600*hs+60*(ms+interv+clen*i/msg_raz)) and (not bool4l) and bool5l and bool6l:
# await contest_msg(i)
return

@tasks.loop(time=create_time(hour=hgn, minute=mgn-5, tzinfo=tz_jst))
async def on_bedtime():
channel = bot.get_channel(channelid)
await channel.send('みんな寝る時間ですよ!おやすみー!また明日!')

#変数読み込み
load_vars()
Expand All @@ -677,12 +685,16 @@ async def loop():
# contesting=int(dbv.loc['contesting','variables'])
# num_ra=int(dbv.loc['num_ra','variables'])

#ループ処理実行
loop.start()

# Botの起動とDiscordサーバーへの接続
#ループ処理実行
async def run():
await asyncio.gather(
on_contest_start.start(),
on_contest_end.start(),
on_bedtime.start(),
bot.start(TOKEN)
)
asyncio.run(run())


bot.run(TOKEN)
# client.run(TOKEN)

18 changes: 18 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
FROM python:3.10-bullseye as builder

WORKDIR /app

COPY requirements.lock /app
RUN pip3 install -r requirements.lock

FROM python:3.10-slim-bullseye as runner

RUN mkdir -p /app/data

COPY --from=builder /usr/local/lib/python3.10/site-packages /usr/local/lib/python3.10/site-packages

COPY AtWaker.py /app

WORKDIR /app

CMD ["python", "-u", "/app/AtWaker.py"]
1 change: 0 additions & 1 deletion Procfile

This file was deleted.

11 changes: 11 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
version: '3'

services:
atwaker:
image: ghcr.io/v-u-d/atwaker:latest
volumes:
- ./data:/app/data
environment:
- TOKEN
- CHANNEL
- SERVER
8 changes: 0 additions & 8 deletions r.py

This file was deleted.

15 changes: 15 additions & 0 deletions requirements.lock
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
aiohttp==3.8.1
aiosignal==1.2.0
async-timeout==4.0.2
attrs==22.1.0
charset-normalizer==2.1.1
discord.py==2.0.1
frozenlist==1.3.1
idna==3.3
multidict==6.0.2
numpy==1.23.3
pandas==1.4.4
python-dateutil==2.8.2
pytz==2022.2.1
six==1.16.0
yarl==1.8.1
1 change: 0 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
discord.py
pandas
numpy
redis
1 change: 0 additions & 1 deletion runtime.txt

This file was deleted.

0 comments on commit 04f18f4

Please sign in to comment.