Skip to content

Commit

Permalink
Merge pull request #18 from Yuuzi261/develope
Browse files Browse the repository at this point in the history
Bug fixes and performance enhancements
  • Loading branch information
Yuuzi261 authored Nov 5, 2023
2 parents d282f61 + 4e3c70e commit 83076b3
Show file tree
Hide file tree
Showing 6 changed files with 55 additions and 18 deletions.
17 changes: 16 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -112,14 +112,29 @@ tasks_monitor_check_period: 60 # Interval at which to check if each tasks i
tasks_monitor_log_period: 14400 # Interval at which to output the list of currently running tasks to the execution log.
```
### 3. Run the bot
### 3. Run and invite the bot to your server
```shell
python bot.py
```

In certain operating systems, you may need to use `python3` instead of `python`.

🔧Bot Permissions Setup `2147666944`

- [x] Read Messages/View Channels
- [x] Send Messages
- [x] Embed Links
- [x] Attach Files
- [x] Mention Everyone
- [x] Use Slash Commands

### 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!

## 💪Contributors

This project exists thanks to all the people who contribute.

[![](https://contrib.rocks/image?repo=Yuuzi261/Tweetcord)](https://github.com/Yuuzi261/Tweetcord/graphs/contributors)
17 changes: 13 additions & 4 deletions README_zh.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,7 @@ Tweetcord是一個discord機器人,它使用tweety-ns模組讓你在discord上
pip install -r requirements.txt
```

在某些作業系統中,你可能需要使用`pip3`而不是`pip`來進行安裝。
在某些作業系統中,你可能需要使用 `pip3` 而不是 `pip` 來進行安裝。

## ⚡使用

Expand Down Expand Up @@ -112,14 +112,23 @@ tasks_monitor_check_period: 60 # 檢查每個任務是否正常運行的間
tasks_monitor_log_period: 14400 # 將當前運行中的任務列表輸出到執行日誌的間隔。
```
### 3. 運行機器人
### 3. 運行機器人並邀請至你的伺服器
```shell
python bot.py
```

在某些操作系統中,你可能需要使用`python3`而不是`python`
在某些操作系統中,你可能需要使用 `python3` 而不是 `python`

🔧機器人權限設定 `2147666944`

- [x] 讀取訊息(Read Messages/View Channels)
- [x] 發送訊息(Send Messages)
- [x] 嵌入連結(Embed Links)
- [x] 附加檔案(Attach Files)
- [x] 提及 @everyone@here 和所有身分組(Mention Everyone)
- [x] 使用應用程式命令(Use Slash Commands)

### 4. 玩得開心

現在你可以回到Discord,並使用`/add notifier`指令來設置你想要接收更新的Twitter用戶!
現在你可以回到Discord,並使用 `/add notifier` 指令來設置你想要接收更新的Twitter用戶!
1 change: 1 addition & 0 deletions src/db_function/init_db.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import sqlite3

def init_db():
os.mkdir(os.getenv('DATA_PATH'))
conn = sqlite3.connect(f"{os.getenv('DATA_PATH')}tracked_accounts.db")
cursor = conn.cursor()
cursor.executescript("""
Expand Down
16 changes: 9 additions & 7 deletions src/notification/account_tracker.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
from src.log import setup_logger
from src.notification.display_tools import gen_embed, get_action
from src.notification.get_tweets import get_tweets
from src.notification.date_comparator import date_comparator
from src.db_function.db_executor import execute
from configs.load_configs import configs

Expand Down Expand Up @@ -48,22 +47,25 @@ async def notification(self, username):

task = asyncio.create_task(asyncio.to_thread(get_tweets, self.tweets, username))
await task
lastest_tweet = task.result()
if lastest_tweet == None: continue
lastest_tweets = task.result()
if lastest_tweets == None: continue

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

user = cursor.execute('SELECT * FROM user WHERE username = ?', (username,)).fetchone()
if date_comparator(lastest_tweet.created_on, user['lastest_tweet']) == 1:
execute(conn, 'UPDATE user SET lastest_tweet = ? WHERE username = ?', (str(lastest_tweet.created_on), username), username)
execute(conn, 'UPDATE user SET lastest_tweet = ? WHERE username = ?', (str(lastest_tweets[-1].created_on), username), username)
for tweet in lastest_tweets:
log.info(f'find a new tweet from {username}')
for data in cursor.execute('SELECT * FROM notification WHERE user_id = ? AND enabled = 1', (user['id'],)):
channel = self.bot.get_channel(int(data['channel_id']))
if channel != None:
mention = f"{channel.guild.get_role(int(data['role_id'])).mention} " if data['role_id'] != '' else ''
await channel.send(f"{mention}**{lastest_tweet.author.name}** just {get_action(lastest_tweet)} here: \n{lastest_tweet.url}", file = discord.File('images/twitter.png', filename='twitter.png'), embeds = gen_embed(lastest_tweet))
try:
mention = f"{channel.guild.get_role(int(data['role_id'])).mention} " if data['role_id'] != '' else ''
await channel.send(f"{mention}**{tweet.author.name}** just {get_action(tweet)} here: \n{tweet.url}", file = discord.File('images/twitter.png', filename='twitter.png'), embeds = gen_embed(tweet))
except Exception as e:
if not isinstance(e, discord.errors.Forbidden): log.error(f'an unexpected error occurred at {channel.mention} while sending notification')

conn.close()

Expand Down
3 changes: 2 additions & 1 deletion src/notification/display_tools.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
import discord
import re

def gen_embed(tweet):
author = tweet.author
embed = discord.Embed(title=f'{author.name} {get_action(tweet, disable_quoted=True)} {get_tweet_type(tweet)}', description=tweet.text, url=tweet.url, color=0x1da0f2, timestamp=tweet.created_on)
embed.set_author(name=f'{author.name} (@{author.username})', icon_url=author.profile_image_url_https, url=f'https://twitter.com/{author.username}')
embed.set_thumbnail(url=author.profile_image_url_https[:-10]+'400x400.jpg')
embed.set_thumbnail(url=re.sub(r'normal(?=\.jpg$)', '400x400', tweet.author.profile_image_url_https))
embed.set_footer(text='Twitter', icon_url='attachment://twitter.png')
if len(tweet.media) == 1:
embed.set_image(url=tweet.media[0].media_url_https)
Expand Down
19 changes: 14 additions & 5 deletions src/notification/get_tweets.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,15 @@
import os
import sqlite3
from src.notification.date_comparator import date_comparator

def get_tweets(tweets, username):
tweets = [tweet for tweet in tweets if tweet.author.username == username]
if tweets != []:
return sorted(tweets, key=lambda x: x.created_on, reverse=True)[0]
else:
return None

conn = sqlite3.connect(f"{os.getenv('DATA_PATH')}tracked_accounts.db")
cursor = conn.cursor()
last_tweet_at = cursor.execute('SELECT lastest_tweet FROM user WHERE username = ?', (username,)).fetchone()[0]
conn.close()

tweets = [tweet for tweet in tweets if tweet.author.username == username and date_comparator(tweet.created_on, last_tweet_at) == 1]

if tweets != []: return sorted(tweets, key=lambda x: x.created_on)
else: return None

0 comments on commit 83076b3

Please sign in to comment.