Rewrite from python to bash

This commit is contained in:
NaiJi ✨ 2022-04-16 00:47:19 +00:00
parent 8635305740
commit 1f8f87a12d
9 changed files with 13 additions and 248 deletions

3
.gitignore vendored
View File

@ -2,4 +2,5 @@
/venv /venv
/urls /urls
/sources /sources
/arts /arts
*.log

View File

@ -6,45 +6,7 @@ Currently posting on: https://udongein.xyz/reisen
### Initial setup ### Initial setup
We support you to create a virtualenv to not pollute your system with modules: * Create sfw/ and nsfw/ folders and fill them with arts.
* Fill token.dat with bot's auth token.
```shell * Edit post-local.sh and write custom text. in "status" field of POST json.
python3 -m venv venv * Now put it to crontab!
source venv/bin/activate
pip install -r requirements.txt
```
Once it's done, you have to create a file `token.dat` in put in the account authorization's key. (no instruction given, it changes between your fediverse software).
Edit the `api_base_url` variable in `post-local.py` and `post-danbooru.py` sources. It must contain the url of the instance your bot is going to post on.
#### `post-local.py`
Allows you to post random arts from your local `/source` folder.
* Create `source` folder in the same location with the `post-local.py` script.
* If you want to download a huge chunk of arts to your folder first, in `download.py` edit global variable `TAGS`, write in there 2 tags you need. Now run
```bash
python3 download.py
```
* In `post-local.py` edit `toot` variable, write in there a string you want the bot to write with any post. Hastags, for example.
* To make a single post, now run
```bash
python3 post-local.py
```
#### `post-danbooru.py`
Allows you to repost random arts from danbooru.donmai.us
* Edit `tags.dat` file. You can look at already defined tags and use it as example
```
#first line is for tags you want to search the arts with (must be exactly 2)
#second line is for tags you decline from posting completely (as many as you want)
#third line is for tags you want mastodon to mark as sensitive (as many as you want)
```
* To make a single post, now run
```bash
python3 post-danbooru.py
```

View File

@ -1,60 +0,0 @@
import requests
import sys
import os.path as op
TAGS = '1girl reisen_udongein_inaba'
def main():
PAGE = 0
rejected_once = False
while True:
URL = "https://danbooru.donmai.us/posts.json"
PARAMS = { 'tags': TAGS,
'page': PAGE }
r = requests.get(url = URL, params = PARAMS)
data = r.json()
# If didn't receive a single entity, we should try again.
# If failed another time, shutdown!
if data.count == 0:
if rejected_once == True:
return
rejected_once = True
continue
rejected_once = False
for entity in data:
if entity['rating'] != 's':
continue
file_tags = entity['tag_string']
# we don't want comics
if 'comic' in file_tags:
continue
try:
file_url = entity['file_url']
except:
continue
# write the art
img_data = requests.get(file_url).content
with open('source/' + file_url[file_url.rfind("/")+1:], 'wb') as handler:
handler.write(img_data)
# save its url separately into a file
with open('urls', 'a', encoding='utf-8') as file:
print(file_url, file=file)
PAGE += 1
# end while True
if __name__ == '__main__':
sys.exit(main())

View File

@ -1,82 +0,0 @@
import requests
import sys
import os.path as op
from mastodon import Mastodon
# --------------------------------------------------
def main():
mastodon = Mastodon(
access_token = 'token.dat',
api_base_url = 'https://udongein.xyz/'
)
with open('tags.dat', 'r') as dat:
tags = dat.readlines()
URL = "https://danbooru.donmai.us/posts.json"
LIMIT = 10
MIN_SCORE = 25
SAFETY = 's'
TAGS_POST = tags[0].strip()
TAGS_FORBID = tags[1].strip().split()
TAGS_SENSITIVE = tags[2].strip().split()
PARAMS = { 'tags': TAGS_POST,
'limit': LIMIT,
'random': True }
print('[start] Settings:')
print('LIMIT = ' + str(LIMIT) + ' | MIN_SCORE = ' + str(MIN_SCORE) + ' | SAFETY = ' + SAFETY)
print('TAGS_POST=' + str(TAGS_POST))
print('TAGS_FORBID=' + str(TAGS_FORBID))
print('TAGS_SENSITIVE=' + str(TAGS_SENSITIVE) + '\n')
# --------------------------------------------------
counter = 1
b_search = True
while b_search:
r = requests.get(url = URL, params = PARAMS)
print('[get] Attempt N' + str(counter) + '.')
data = r.json()
for i in range(0, LIMIT):
fileurl = data[i]['file_url']
print('url ', fileurl)
fileid = data[i]['id']
print('id ', fileid)
filescore = data[i]['fav_count']
print('score ', filescore)
filesafe = data[i]['rating']
print('rating ', filesafe)
filetagstring = data[i]['tag_string']
print('tags ', filetagstring)
pulledtags = filetagstring.split()
if (filesafe == SAFETY and filescore >= MIN_SCORE
and not set(pulledtags).intersection(TAGS_FORBID)):
print('[success] Found!')
b_search = False
break
# --------------------------------------------------
fformat = op.splitext(fileurl)[1][1:]
if (fformat == 'jpg'):
fformat = 'jpeg'
media = mastodon.media_post(requests.get(fileurl).content, f'image/{fformat}')
toot = f'This is just a test post nevermind thisjksajskkj.... https://danbooru.donmai.us/posts/{fileid}'
b_sensetive = bool(set(pulledtags).intersection(TAGS_SENSITIVE))
if (b_sensetive):
print('[success] Marked as sensitive.')
mastodon.status_post(toot, media_ids=[media], visibility='unlisted', sensitive=b_sensetive)
print('[success] Posted!\n----------------------------------\n')
if __name__ == '__main__':
sys.exit(main())

View File

@ -1,53 +0,0 @@
#!/home/naiji/mastodon/udonge-bot/venv/bin/python
import requests
import sys
import random
import os
import os.path as op
from mastodon import Mastodon
from datetime import datetime
# --------------------------------------------------
DIR_SFW = 'sfw/'
DIR_NSFW = 'nsfw/'
def main():
mastodon = Mastodon(
access_token = 'token.dat',
api_base_url = 'https://udongein.xyz/'
)
sfwcount = len([name for name in os.listdir(DIR_SFW) if os.path.isfile(os.path.join(DIR_SFW, name))])
nsfwcount = len([name for name in os.listdir(DIR_NSFW) if os.path.isfile(os.path.join(DIR_NSFW, name))])
random_choice = random.randint(1, sfwcount + nsfwcount)
print('\ns:' + str(sfwcount) + ' n:' + str(nsfwcount) + ' r:' + str(random_choice))
is_safe = False if random_choice < nsfwcount else True
art = ""
if is_safe:
files = [f for f in os.listdir(DIR_SFW) if op.isfile(op.join(DIR_SFW, f))]
art = DIR_SFW + random.choice(files)
else:
files = [f for f in os.listdir(DIR_NSFW) if op.isfile(op.join(DIR_NSFW, f))]
art = DIR_NSFW + random.choice(files)
fformat = op.splitext(art)[1][1:]
if (fformat == 'jpg'):
fformat = 'jpeg'
with open(art, 'rb') as picture:
data = picture.read()
media = mastodon.media_post(data, f'image/{fformat}')
toot = f':gyate_reisen_love:'
mastodon.status_post(toot, media_ids=[media], visibility='unlisted', sensitive=not is_safe)
print(str(datetime.now()) + ': ' + art)
if __name__ == '__main__':
sys.exit(main())

View File

@ -25,10 +25,13 @@ then
is_sensitive=false is_sensitive=false
fi fi
media_json=$(curl -X POST "${api_base_url}/api/v1/media" -H "Authorization: Bearer ${access_token}" -F "file=@${source_url}") media_json=$(curl -X POST "${api_base_url}/api/v1/media" \
-H "Authorization: Bearer ${access_token}" \
-F "file=@${source_url}")
media_id=$(jq -r ".id" <<< ${media_json}) media_id=$(jq -r ".id" <<< ${media_json})
curl -X POST -d '{"status":" :gyate_reisen_love:", "sensitive":'${is_sensitive}', "visibility":"'unlisted'", "media_ids":'[\"${media_id}\"]'}' \ curl -X POST -d '{"status":" :gyate_reisen_love:", "sensitive":'${is_sensitive}', "visibility":"'unlisted'", "media_ids":'[\"${media_id}\"]'}' \
-H "Authorization: Bearer ${access_token}" \ -H "Authorization: Bearer ${access_token}" \
-H "Content-Type: application/json" \ -H "Content-Type: application/json" \
"${api_base_url}/api/v1/statuses" "${api_base_url}/api/v1/statuses"

View File

@ -1 +0,0 @@
mastodon.py

2
runner
View File

@ -1,2 +0,0 @@
#!/home/naiji/mastodon/udonge-bot/venv/bin/python
python3 post-local.py

View File

@ -1,3 +0,0 @@
reisen_udongein_inaba 1girl
blood nazi unhappy comic
swimsuit ass large_breasts underwear