# LSA 期末 telegram-bot & k8s wordpress
[TOC]
## telegram_bot
### 建立 telegram-bot
* 到 [@BotFather](https://t.me/BotFather) 申請

* 輸入 /newbot 建立 bot
* 接下來依序輸入 bot 的名稱、username
* 最後記下 BotFather 回傳的 token

### bot 接收指令程式碼
* 從網路上找對應程式語言的 telegram-bot 範例程式碼來修改
> 這邊使用 [python-telegram-bot](https://python-telegram-bot.org/)
```python=1
from telegram import Update
from telegram.ext import ApplicationBuilder, CommandHandler, ContextTypes
async def hello(update: Update, context: ContextTypes.DEFAULT_TYPE) -> None:
await update.message.reply_text(f'Hello {update.effective_user.first_name}')
app = ApplicationBuilder().token("YOUR TOKEN HERE").build()
app.add_handler(CommandHandler("hello", hello))
app.run_polling()
```
* 建立函式並把指令名稱和函式名稱加到`app.add_handler(CommandHandler("{指令名}","{函式名}"))`
* 之後在 telegram 中只要對 bot 下`/{指令名}`,就會去執行對應的函式
* 安裝 python-telegram-bot 套件
`pip3 install python-telegram-bot`
* 執行程式 bot 就會開始運作了
`python3 {檔名.py}`
### bot 主動發訊息程式碼
```python=1
import requests
def main():
# bot token
token = "{bot token}"
# 使用者 id
chat_id="{使用者id}"
# 訊息
message = "{訊息}"
url = f"https://api.telegram.org/bot{token}/sendMessage?chat_id={chat_id}&text={message}"
requests.get(url) # this sends the message
main()
```
## python 操作 k8s 建立 wordpress & mysql
### 安裝套件
* Kubernetes Python
`pip3 install kubernetes`
* 可以直接在 python 讀取 .yaml,需要安裝 pyYAML
`pip3 install YAML`
### 範例程式
```python=1
from kubernetes import client, config
import yaml
# 讀取k8s config檔,如果是用snap安裝microk8s,路徑為/var/snap/microk8s/current/credentials/client.config
# 其他安裝方法路徑可能會是$HOME/.kube/config
config.load_kube_config(config_file="/var/snap/microk8s/current/credentials/client.config")
# 設定api version
v1 = client.AppsV1Api() # deployment
v1 = client.CoreV1Api() # pod,service
# 新增pod
#pod = client.V1Pod()
# 設定pod的metadata等資訊
#pod.metadata = client.V1ObjectMeta(name="my-pod")
#pod.spec = client.V1PodSpec(
#containers = [
#client.V1Container(
#name = "my-container",
#image = "nginx:latest",
#ports = [client.V1ContainerPort(container_port=80)]
#)
#]
#)
#v1.create_namespaced_pod(namespace="default",body=pod)
# get all pod
#allPod = v1.list_pod_for_all_namespaces(watch=False)
#for pod in allPod.items:
#print(f"{pod.metadata.namespace}: {pod.metadata.name}")
# load yaml
with open("wordpress-service.yaml","r") as file:
yaml_file = yaml.safe_load(file)
# create deployment
#v1.create_namespaced_deployment(
#body = yaml_file,
#namespace = "default"
#)
# create service
v1.create_namespaced_service(
body=yaml_file,
namespace = "default"
)
```
