Compare commits

...

3 Commits

8 changed files with 73 additions and 68 deletions

3
.gitignore vendored
View File

@@ -2,4 +2,5 @@ bin/
.vscode/
obj/
*.log
*.json
*.json
.env

View File

@@ -7,9 +7,11 @@ public class MastodonBot
{
private static Timer _timer;
private static async Task Main()
{
DotNetEnv.Env.Load();
// Configure logging
using var loggerFactory = LoggerFactory.Create(builder =>
{
@@ -17,8 +19,12 @@ public class MastodonBot
});
var logger = loggerFactory.CreateLogger<MastodonBot>();
if(!CheckEnv.IsValid()){
logger.LogCritical("Error reading envinonment variables, either some values are missing or no .env file was found");
throw new Exception("Error reading envinonment variables, either some values are missing or no .env file was found");
}
// Setup DB
var db = await DbInitializer.SetupDb(Environment.GetEnvironmentVariable("DB_NAME"));
var db = await DbInitializer.SetupDb(DotNetEnv.Env.GetString("DB_NAME"));
if (db == null)
{
logger.LogCritical("Unable to setup DB");
@@ -27,26 +33,31 @@ public class MastodonBot
logger.LogInformation("DB setup done");
// Setup bot
var bot = new TelegramBotClient(Environment.GetEnvironmentVariable("BOT_TOKEN"));
var me = await bot.GetMeAsync();
await bot.DropPendingUpdatesAsync();
logger.LogInformation($"Bot is running as {me.FirstName}.");
bot.OnUpdate += OnUpdate;
var bot = new TelegramBotClient(DotNetEnv.Env.GetString("BOT_TOKEN"));
// Handle bot updates
async Task OnUpdate(Update update)
{
switch (update)
var me = await bot.GetMeAsync();
await bot.DropPendingUpdatesAsync();
bot.OnUpdate += OnUpdate;
logger.LogInformation($"Bot is running as {me.FirstName}.");
// Handle bot updates
async Task OnUpdate(Update update)
{
case { CallbackQuery: { } callbackQuery }: await HandlePostAction.HandleCallbackQuery(callbackQuery,db,bot, logger); break;
default: logger.LogInformation($"Received unhandled update {update.Type}"); break;
};
}
switch (update)
{
case { CallbackQuery: { } callbackQuery }: await HandlePostAction.HandleCallbackQuery(callbackQuery, db, bot, logger); break;
default: logger.LogInformation($"Received unhandled update {update.Type}"); break;
};
}
// Set a timer to fetch and process posts every 15 minutes
_timer = new Timer(async _ => await RunCheck.runAsync(db, bot, Environment.GetEnvironmentVariable("TAG"),logger,Environment.GetEnvironmentVariable("CUSTOM_INSTANCE")), null, TimeSpan.Zero, TimeSpan.FromMinutes(15));
Console.ReadLine();
// Set a timer to fetch and process posts every 15 minutes
_timer = new Timer(async _ => await RunCheck.runAsync(db, bot, DotNetEnv.Env.GetString("TAG"), logger, DotNetEnv.Env.GetString("CUSTOM_INSTANCE")), null, TimeSpan.Zero, TimeSpan.FromMinutes(15));
Console.ReadLine();
}

View File

@@ -31,41 +31,7 @@ I am not responsible for any misuse or unauthorized use of the scraped data. It
**Providing Environment Variables:**
* **Windows:**
- Open a command prompt and navigate to the directory containing the executable.
- Set environment variables before running the program using the `set` command. For example:
```bash
set DB_NAME=my_data.json BOT_TOKEN=your_telegram_bot_token TAG=important_data CHANNEL_NUMID=1234567890 ADMIN_NUMID=9876543210
your_project_name.exe
```
* **macOS/Linux:**
- Open a terminal and navigate to the directory containing the executable.
- Set environment variables before running the program using the `export` command. For example:
```bash
export DB_NAME=my_data.json BOT_TOKEN=your_telegram_bot_token TAG=important_data CHANNEL_NUMID=1234567890 ADMIN_NUMID=9876543210
./your_project_name
```
**Replace `your_project_name` with the actual name of the downloaded executable file and your own environment variable values.**
### Using `dotnet run`
1. Ensure you have .NET 8 installed on your system.
2. Open a terminal and navigate to the root directory of your project where the `.csproj` file resides.
**Providing Environment Variables:**
There are two ways to provide environment variables when using `dotnet run`:
**A. Using the `DOTNET_VARIABLES` environment variable:**
Set the `DOTNET_VARIABLES` environment variable to a semicolon-separated list of key-value pairs for your environment variables. For example:
```bash
export DOTNET_VARIABLES="DB_NAME=my_data.json;BOT_TOKEN=your_telegram_bot_token;TAG=important_data;CHANNEL_NUMID=1234567890;ADMIN_NUMID=9876543210"
dotnet run
```
**B. Using a `.env` file:**
**Using a `.env` file:**
1. Create a file named .env in the root directory of your project.
2. Add each environment variable on a separate line in the format KEY=VALUE. For example:
```
@@ -75,8 +41,10 @@ TAG=important_data
CHANNEL_NUMID=1234567890
ADMIN_NUMID=9876543210
```
3. Run the following command:
1. Run the following command:
```bash
dotnet run
or
./mstdnCats
```
**Remember to replace `your_telegram_bot_token`, `my_data.json`, `important_data`, `1234567890`, and `9876543210` with your actual values.**

21
Services/CheckEnv.cs Normal file
View File

@@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace mstdnCats.Services
{
public class CheckEnv
{
public static Boolean IsValid(){
if (DotNetEnv.Env.GetString("DB_NAME") == null ||
DotNetEnv.Env.GetString("BOT_TOKEN") == null ||
DotNetEnv.Env.GetString("TAG") == null ||
DotNetEnv.Env.GetString("CHANNEL_NUMID") == null ||
DotNetEnv.Env.GetString("ADMIN_NUMID") == null ){
return false;
}
return true;
}
}
}

View File

@@ -9,19 +9,22 @@ namespace mstdnCats.Services
{
// Setup DB
IDocumentCollection<Post>? collection = null;
try
if (_dbname != null)
{
// Initialize DB
var store = new DataStore($"{_dbname}.json", minifyJson: false);
collection = store.GetCollection<Post>();
}
catch
{
return Task.FromResult<IDocumentCollection<Post>>(null);
}
try
{
// Initialize DB
var store = new DataStore($"{_dbname}.json", minifyJson: false);
collection = store.GetCollection<Post>();
}
catch
{
return Task.FromResult<IDocumentCollection<Post>>(null);
}
// Return collection
// Return collection
return Task.FromResult(collection);
}
return Task.FromResult(collection);
}
}

View File

@@ -44,7 +44,7 @@ namespace mstdnCats.Services
if (updated)
{
// Send the media attachment to the channel
await _bot.SendPhotoAsync(Environment.GetEnvironmentVariable("CHANNEL_NUMID"), post.MediaAttachments.First().Url, caption: $"Post from " + $"<a href=\"" + post.Account.Url + "\">" + post.Account.DisplayName + " </a>", parseMode: ParseMode.Html
await _bot.SendPhotoAsync(DotNetEnv.Env.GetString("CHANNEL_NUMID"), post.MediaAttachments.First().Url, caption: $"Post from " + $"<a href=\"" + post.Account.Url + "\">" + post.Account.DisplayName + " </a>", parseMode: ParseMode.Html
, replyMarkup: new InlineKeyboardMarkup(InlineKeyboardButton.WithUrl("View on Mastodon", post.Url)));
await _bot.AnswerCallbackQueryAsync(callbackQuery.Id, "Media attachment approved and sent to channel.");

View File

@@ -24,7 +24,7 @@ namespace mstdnCats.Services
// Send approve or reject message to admin
foreach (var media in post.MediaAttachments)
{
await _bot.SendPhotoAsync(Environment.GetEnvironmentVariable("ADMIN_NUMID"), media.PreviewUrl, caption: $"<a href=\"" + post.Url + "\"> Mastodon </a>", parseMode: ParseMode.Html
await _bot.SendPhotoAsync(DotNetEnv.Env.GetString("ADMIN_NUMID"), media.PreviewUrl, caption: $"<a href=\"" + post.Url + "\"> Mastodon </a>", parseMode: ParseMode.Html
, replyMarkup: new InlineKeyboardMarkup().AddButton("Approve", $"approve-{media.MediaId}").AddButton("Reject", $"reject-{media.MediaId}"));
}

View File

@@ -9,6 +9,7 @@
</PropertyGroup>
<ItemGroup>
<PackageReference Include="DotNetEnv" Version="3.1.1" />
<PackageReference Include="JsonFlatFileDataStore" Version="2.4.2" />
<PackageReference Include="Telegram.Bot" Version="21.11.0" />
</ItemGroup>