---
# System prepended metadata

title: '[python] 值班表通知腳本'
tags: [腳本, 值班表]

---

# [python] 值班表通知腳本
###### tags: `腳本` `值班表`

## :triangular_flag_on_post: 使用狀況

:::warning
排班人員上班以及上班時間
:::

- 目前只有用讀取excel google sheet尚未連結使用
- 如果需要修改稍微麻煩 

### :small_blue_diamond: 套件
| pip3 list       | 功能            |
| --------------- |:--------------:|
|openpyxl 3.0.10 |讀取excel套件|
|python-telegram-bot 13.12 |tg告警|
|pytz 2022.2.1|時區計算套件|

## :feet: 值班腳本 (含有變化居家值班)

```python=
import time
import pytz
import datetime
import openpyxl
import telegram

#定義 
#dic 對應 班別去判斷上班時間
dic = { "早" : "8:00~17:00" , "中" : "14:00~23:00", "夜" : "23:00~08:00", "行" : "10:00~19:00" }
dic2 = { "居早" : "8:00~17:00" , "居中" : "14:00~23:00", "居夜" : "23:00~08:00", "居行" : "10:00~19:00" }
#ServiceTime 定時任務對應到的班別
ServiceTime = { "8" : "早" , "10" : "行", "14" : "中" , "23" : "夜"}
ServiceTime2 = { "8" : "居早" , "10" : "居行", "14" : "居中" , "23" : "居夜"}

#變數
#時區 年月日天小時
tw = pytz.timezone('Asia/Taipei')
year = datetime.datetime.now(tw).timetuple().tm_year
month = datetime.datetime.now(tw).timetuple().tm_mon
day = datetime.datetime.now(tw).timetuple().tm_mday
hour = datetime.datetime.now(tw).timetuple().tm_hour
num = 1 + day

#讀取xlsx
workbook = openpyxl.load_workbook('/alldata/work/yw-work.xlsx')
sheet = workbook.active

#TGt傳送字串 workShift定義
workShift = "日期:" + str(month) + "/" + str(day) + "\n"
#workShift += "运维值班人員: "

#判斷用 定義title 跟 check
title = sheet.cell(row=2, column=num).value
check = str(day)

#下面是各種寫法
#check = str(year) + "-" + str("%02d" % month) + "-" + str(day) + " " + "00:00:00"
#check = str(day) + ".0"


#判斷式
if str(title) == str(check):
    for i in range(2,21):
        if sheet.cell(row=i, column=num).value == ServiceTime[str(hour)]:
          workShift +="\n"+ "运维值班人員: "
          workShift += sheet.cell(row=i, column=1).value + " "
        elif sheet.cell(row=i, column=num).value == ServiceTime2[str(hour)]:
          workShift +="\n"+"居家值班人員: "
          workShift += sheet.cell(row=i, column=1).value + "\n"
    workShift += "\n" + "服务时间:" + dic[ServiceTime[str(hour)]] + "\n"
    workShift += " \n"
 
else:
     workShift = "班表表單順序錯囉，或是程式錯拉QQ"
        
#tg機器token
bot = telegram.Bot(token='1033770595:AAH6-wqoOw37Z2A5LQruDQTt-c9cmcoLdtA')

#larry測試
#bot.sendMessage(chat_id='-651507342', text=workShift)

#純工作群
#bot.sendMessage(chat_id='-509512827', text=workShift)

#OPSTW
bot.sendMessage(chat_id='-1001589110734', text=workShift)
```

## :triangular_flag_on_post: 班表配置形式
![](https://i.imgur.com/AMnjbrK.png)

## :triangular_flag_on_post: 腳本執行結果

![](https://i.imgur.com/blCNH7g.png)
