Skip to content

Commit

Permalink
Merge pull request #24 from Yuuzi261/develope
Browse files Browse the repository at this point in the history
0.4.0
  • Loading branch information
Yuuzi261 authored Jan 24, 2024
2 parents 98c511f + 719dc8b commit 5a2e42a
Show file tree
Hide file tree
Showing 14 changed files with 397 additions and 44 deletions.
98 changes: 98 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,25 @@ Tweetcord is a discord bot that uses the tweety-ns module to let you receive twe

- List all twitter users whose notifications are enabled on the current server

👉 `/sync` _(new in 0.4)_

- Sync the notification of new Twitter account with database. If you change the twitter account used by bot, please use this command

👉 `/customize message` `username` `channel` | `default` _(new in 0.4)_

| parameters | types | descriptions |
| --------- | ----- | ----------- |
| `username` | str | The username of the twitter user you want to set customized message |
| `channel` | discord.TextChannel | The channel which set to delivers notifications |
| `default` | bool | Whether to use default setting _(default is false)_ |

There are currently 4 special variables that can be used in customized messages, which will be explained below.

- `{action}` : poster's action, include `tweeted`, `retweeted` and `quoted`
- `{author}` : poster's display name
- `{mention}` : the role to mention when sending to discord
- `{url}` : the link of the tweet

</details>

## 📥Installation
Expand All @@ -70,6 +89,50 @@ In certain operating systems, you may need to use the command `pip3` instead of

**📢This tutorial is suitable for version 0.3.2 or later. (Recommended: 0.3.5 or later)**

<details>
<summary><b>📌click here to upgrade from 0.3.5 to 0.4.0</b></summary>

⚠️Before everything starts you must upgrade the version of `tweety-ns` to `1.0.9.2` first and download or pull the new code from this repo.

Create a python file in the `cogs` folder and name it `upgrade.py`. Paste the following code and run the bot. Use the slash command `/upgrade version` to upgrade. This cog can be removed after the upgrade is completed.

```py
import discord
from discord import app_commands
from core.classes import Cog_Extension
import sqlite3
import os

from src.permission import ADMINISTRATOR

class Upgrade(Cog_Extension):

upgrade_group = app_commands.Group(name='upgrade', description='Upgrade something', default_permissions=ADMINISTRATOR)

@upgrade_group.command(name='version', description='upgrade to Tweetcord 0.4.0')
async def upgrade(self, itn: discord.Interaction):

await itn.response.defer(ephemeral=True)

conn = sqlite3.connect(f"{os.getenv('DATA_PATH')}tracked_accounts.db")
cursor = conn.cursor()

try:
cursor.executescript("""
ALTER TABLE user ADD enabled INTEGER DEFAULT 1;
ALTER TABLE notification ADD customized_msg TEXT DEFAULT NULL;
""")
await itn.followup.send('successfully upgrade to 0.4.0, you can remove this cog and reboot the bot.')
except:
await itn.followup.send('upgrading to 0.4.0 failed, please try again or contact the author.')


async def setup(bot):
await bot.add_cog(Upgrade(bot))
```

</details>

<details>
<summary><b>📌click here to upgrade from 0.3.4 to 0.3.5</b></summary>

Expand Down Expand Up @@ -167,6 +230,8 @@ tweets_check_period: 10 # The check frequency for the posts (it is n
tweets_updater_retry_delay: 300 # Retry Interval when Tweets Updater encounters exceptions (e.g., rate limitations).
tasks_monitor_check_period: 60 # Interval at which to check if each tasks is functioning properly, and if a task has stopped, attempt a restart.
tasks_monitor_log_period: 14400 # Interval at which to output the list of currently running tasks to the execution log.
auto_turn_off_notification: true # (v0.4.0 or later) If all notifications for a user are disabled, decide whether to unfollow the user.
auto_unfollow: true # (v0.4.0 or later) If all notifications for a user is disabled, decide whether to disable notification for the user (twitter side).
```
### 3. Run and invite the bot to your server
Expand All @@ -186,6 +251,39 @@ In certain operating systems, you may need to use `python3` instead of `python`.
- [x] Mention Everyone
- [x] Use Slash Commands

> [!NOTE]
> If you want to host the bot on a server, here is a recommended service that is basically free: [fly.io](https://fly.io).
<details>
<summary><b>⚙️some configuration files you may need if you use fly.io</b></summary>

- dockerfile

```dockerfile
FROM python:3.10.9
WORKDIR /bot
COPY requirements.txt /bot/
RUN pip install -r requirements.txt
COPY . /bot/
CMD python bot.py
```

- fly.toml

```toml
app = "YOUR_APP_NAME"
primary_region = "YOUR_APP_REGION"

[env]
DATA_PATH = "/data/"

[mounts]
source = "YOUR_APP_VOLUME_NAME"
destination = "/data"
```

</details>

### 4. Have fun

Now you can go back to Discord and use the `/add notifier` command to set up notifications for the Twitter users you wish to receive updates from!
Expand Down
98 changes: 98 additions & 0 deletions README_zh.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,25 @@ Tweetcord是一個discord機器人,它使用tweety-ns模組讓你在discord上

- 列出所有當前伺服器開啟通知的Twitter用戶

👉 `/sync` _(0.4版本的新功能)_

- 將新Twitter帳戶的通知與資料庫同步。如果你更改了bot使用的Twitter帳戶,請使用此指令

👉 `/customize message` `username` `channel` | `default` _(0.4版本的新功能)_

| 參數 | 類型 | 描述 |
| --------- | ----- | ----------- |
| `username` | str | 你想要設定自定義通知訊息的Twitter用戶的用戶名 |
| `channel` | discord.TextChannel | 機器人發送通知的頻道 |
| `default` | bool | 是否要還原至預設的設定 _(預設是false)_ |

目前自定義通知訊息有4種特別的變數可以使用,將在下面說明:

- `{action}` : 發文者的動作, 包括 `tweeted`, `retweeted``quoted` _(暫不支持中文)_
- `{author}` : 發文者的顯示名稱
- `{mention}` : 發送到discord時提及的身份組
- `{url}` : 推文的連結

</details>

## 📥安裝
Expand All @@ -70,6 +89,50 @@ pip install -r requirements.txt

**📢本教學適用於0.3.2或更高版本。(建議:0.3.5或更高版本)**

<details>
<summary><b>📌0.3.5升級到0.4.0請點這裡</b></summary>

⚠️在一切開始之前請先更新 `tweety-ns``1.0.9.2` 版本並且從這個repo下載或拉取新的程式碼。

`cogs` 資料夾創建一個python檔案並命名為 `upgrade.py`,貼上下面的程式碼並運行機器人,使用斜線指令 `/upgrade version` 進行升級。升級結束後可以移除這個cog。

```py
import discord
from discord import app_commands
from core.classes import Cog_Extension
import sqlite3
import os

from src.permission import ADMINISTRATOR

class Upgrade(Cog_Extension):

upgrade_group = app_commands.Group(name='upgrade', description='Upgrade something', default_permissions=ADMINISTRATOR)

@upgrade_group.command(name='version', description='upgrade to Tweetcord 0.4.0')
async def upgrade(self, itn: discord.Interaction):

await itn.response.defer(ephemeral=True)

conn = sqlite3.connect(f"{os.getenv('DATA_PATH')}tracked_accounts.db")
cursor = conn.cursor()

try:
cursor.executescript("""
ALTER TABLE user ADD enabled INTEGER DEFAULT 1;
ALTER TABLE notification ADD customized_msg TEXT DEFAULT NULL;
""")
await itn.followup.send('successfully upgrade to 0.4.0, you can remove this cog and reboot the bot.')
except:
await itn.followup.send('upgrading to 0.4.0 failed, please try again or contact the author.')


async def setup(bot):
await bot.add_cog(Upgrade(bot))
```

</details>

<details>
<summary><b>📌0.3.4升級到0.3.5請點這裡</b></summary>

Expand Down Expand Up @@ -167,6 +230,8 @@ tweets_check_period: 10 # 檢查推文的頻率(不建議將此值
tweets_updater_retry_delay: 300 # 當Tweets Updater遇到異常(例如速率限制)時的重試間隔。
tasks_monitor_check_period: 60 # 檢查每個任務是否正常運行的間隔,如果某個任務停止了,嘗試重新啟動。
tasks_monitor_log_period: 14400 # 將當前運行中的任務列表輸出到執行日誌的間隔。
auto_turn_off_notification: true # (v0.4.0或更新版本) 如果某個使用者的所有通知都已停用,決定是否取消追蹤該使用者。
auto_unfollow: true # (v0.4.0或更新版本) 如果某個使用者的所有通知都已停用,決定是否停用該使用者的通知(Twitter端)。
```
### 3. 運行機器人並邀請至你的伺服器
Expand All @@ -186,6 +251,39 @@ python bot.py
- [x] 提及 @everyone@here 和所有身分組(Mention Everyone)
- [x] 使用應用程式命令(Use Slash Commands)

> [!NOTE]
> 如果想將機器人架到伺服器上,這裡推薦一個基本免費的服務:[fly.io](https://fly.io).
<details>
<summary><b>⚙️如果你使用fly.io的話你可能會需要的一些配置檔案</b></summary>

- dockerfile

```dockerfile
FROM python:3.10.9
WORKDIR /bot
COPY requirements.txt /bot/
RUN pip install -r requirements.txt
COPY . /bot/
CMD python bot.py
```

- fly.toml

```toml
app = "你的APP名稱"
primary_region = "你的APP地區"

[env]
DATA_PATH = "/data/"

[mounts]
source = "你的APP的VOLUME名稱"
destination = "/data"
```

</details>

### 4. 玩得開心

現在你可以回到Discord,並使用 `/add notifier` 指令來設置你想要接收更新的Twitter用戶!
Expand Down
9 changes: 3 additions & 6 deletions bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,8 @@ async def on_ready():
if not(os.path.isfile(f"{os.getenv('DATA_PATH')}tracked_accounts.db")): init_db()
bot.tree.on_error = on_tree_error
for filename in os.listdir('./cogs'):
if filename.endswith('.py'):
await bot.load_extension(f'cogs.{filename[:-3]}')
if filename.endswith('.py'):
await bot.load_extension(f'cogs.{filename[:-3]}')
log.info(f'{bot.user} is online')
slash = await bot.tree.sync()
log.info(f'synced {len(slash)} slash commands')
Expand Down Expand Up @@ -73,10 +73,7 @@ async def upload_data(ctx : commands.context.Context):

@bot.event
async def on_tree_error(itn : discord.Interaction, error : app_commands.AppCommandError):
if isinstance(error, app_commands.errors.CheckFailure):
await itn.response.send_message('Permission denied.', ephemeral=True)
else:
await itn.response.send_message(error, ephemeral=True)
await itn.response.send_message(error, ephemeral=True)
log.warning(f'an error occurred but was handled by the tree error handler, error message : {error}')


Expand Down
5 changes: 2 additions & 3 deletions cogs/list_users.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,12 @@
import sqlite3
import os

from src.permission_check import is_administrator
from src.permission import ADMINISTRATOR

class ListUsers(Cog_Extension):

list_group = app_commands.Group(name='list', description="List something")
list_group = app_commands.Group(name='list', description='List something', default_permissions=ADMINISTRATOR)

@is_administrator()
@list_group.command(name='users')
async def list_users(self, itn: discord.Interaction):
"""Lists all exists notifier on your server."""
Expand Down
Loading

0 comments on commit 5a2e42a

Please sign in to comment.