1
0
mirror of https://github.com/jeantoulza/scplanner-discord synced 2024-11-23 19:55:37 +01:00

Added comments and more options

This commit is contained in:
Jean TOULZA 2018-04-12 15:03:58 +02:00
parent 1b0e42c538
commit 5790a2b60f
2 changed files with 67 additions and 30 deletions

83
auto.py
View File

@ -16,24 +16,21 @@ BASE = "https://scplanner.net/"
COOKIE_NAME = config["CONFIG"]["cookie_name"] COOKIE_NAME = config["CONFIG"]["cookie_name"]
COOKIE_VALUE = config["CONFIG"]["cookie_value"] COOKIE_VALUE = config["CONFIG"]["cookie_value"]
print(COOKIE_NAME+"="+COOKIE_VALUE)
def get_cookie_jar(): def get_cookie_jar():
try: '''
from cookielib import Cookie, CookieJar # Python 2 Creates a cookie jar for the mechanicalsoup browser
except ImportError: '''
from http.cookiejar import Cookie, CookieJar # Python 3. from http.cookiejar import Cookie, CookieJar
from http.cookies import SimpleCookie cj = CookieJar()
cj = CookieJar() c = Cookie(version=0, name=COOKIE_NAME, value=COOKIE_VALUE, port=None, port_specified=False, domain='scplanner.net',
# Cookie(version, name, value, port, port_specified, domain, domain_specified=True, domain_initial_dot=False, path='/', path_specified=True, secure=False, expires=None, discard=True, comment=None, comment_url=None, rest=None, rfc2109=True)
# domain_specified, domain_initial_dot, path, path_specified, cj.set_cookie(c)
# secure, discard, comment, comment_url, rest) return cj
c = Cookie(version=0, name=COOKIE_NAME, value=COOKIE_VALUE, port=None, port_specified=False, domain='scplanner.net',
domain_specified=True, domain_initial_dot=False, path='/', path_specified=True, secure=False, expires=None, discard=True, comment=None, comment_url=None, rest=None, rfc2109=True)
cj.set_cookie(c)
return cj
def resolve(url): def resolve(url):
'''
Transforms a 'url' into a soundcloud object. False if not found.
'''
client_id = "nF5U0gNsNB8529U1rHetpIywdIlnEKk7" client_id = "nF5U0gNsNB8529U1rHetpIywdIlnEKk7"
client = soundcloud.Client(client_id=client_id) client = soundcloud.Client(client_id=client_id)
try: try:
@ -51,6 +48,9 @@ def resolve(url):
return False return False
def get_client_id(): def get_client_id():
'''
Tricky part to get the current public client_id of SoundCloud's website
'''
body = requests.get("https://soundcloud.com").text body = requests.get("https://soundcloud.com").text
reg_app = r'https:\/\/a-v2\.sndcdn\.com\/assets\/app(.*).js' reg_app = r'https:\/\/a-v2\.sndcdn\.com\/assets\/app(.*).js'
matches = re.search(reg_app,body) matches = re.search(reg_app,body)
@ -86,26 +86,32 @@ def auto(track_url):
try: try:
br.select_form("#autoschForm") br.select_form("#autoschForm")
br["urls"] = track_url br["urls"] = track_url
soup = BeautifulSoup(rep.text, "html.parser")
accounts_select = soup.find("select", {"name": "account[]"}) use_all_accounts = False
accounts = [] try:
for account_option in accounts_select.findAll("option"): if config["AUTO"]["use_all_accounts"] == "yes":
accounts.append(account_option["value"]) soup = BeautifulSoup(rep.text, "html.parser")
br["account[]"] = tuple(accounts) accounts_select = soup.find("select", {"name": "account[]"})
#br["account[]"] = (107375074, 195766419) accounts = []
for account_option in accounts_select.findAll("option"):
accounts.append(account_option["value"])
br["account[]"] = tuple(accounts)
#br["account[]"] = (107375074, 195766419)
except:
pass
rep = br.submit_selected() rep = br.submit_selected()
except: except:
raise Exception("ERROR 131: There was a problem when posting URL on SCPlanner. Is your account still valid?") raise Exception("There was a problem when posting URL on SCPlanner. Is your account still valid?")
rep = rep.text rep = rep.text
rep_json = json.loads(rep) rep_json = json.loads(rep)
if not isinstance(rep_json, list): if not isinstance(rep_json, list):
if rep_json["title"] == "Error S-788": if rep_json["title"] == "Error S-788":
raise Exception("You have not set your account preferences. Please set them here: https://scplanner.net/account") raise Exception("You have probably set use_all_accounts to 'no' and haven't set your account preferences. Please set them here: https://scplanner.net/account")
else: else:
print(rep_json) print(rep_json)
raise Exception("Something weird happened. Please tell Amazed#3330.") raise Exception("Unknown error. Please fill an issue on https://github.com/jeantoulza/scplanner-discord.")
type = rep_json[0]["type"] type = rep_json[0]["type"]
if type == "success" and len(rep_json[0]["success_schedules"]) > 0: if type == "success" and len(rep_json[0]["success_schedules"]) > 0:
group = rep_json[0]["success_schedules"][0]["group"] group = rep_json[0]["success_schedules"][0]["group"]
@ -114,12 +120,23 @@ def auto(track_url):
if track: if track:
return text+"\nSee https://scplanner.net/calendar/reposts/{0}/{1}/{2}".format(soundcloud_id, track.id, group) return text+"\nSee https://scplanner.net/calendar/reposts/{0}/{1}/{2}".format(soundcloud_id, track.id, group)
else: else:
raise Exception("ERROR 312: Schedule was done but I could not find track :( Please PM Amazed#3330.") raise Exception("Schedule was done but I could not find track :(")
else: else:
raise Exception("ERROR 851: Track not found :(") raise Exception("Track not found, or something worse happened :(")
def has_role(user, role):
'''
Returns True if 'user' has the 'role' role, False otherwise.
'''
for u_role in user.roles:
if u_role.name == role:
return True
return False
def start_bot(): def start_bot():
'''
Main bot loop
'''
bot = commands.Bot(command_prefix='!') bot = commands.Bot(command_prefix='!')
@bot.event @bot.event
async def on_ready(): async def on_ready():
@ -128,9 +145,17 @@ def start_bot():
print(bot.user.id) print(bot.user.id)
print('------') print('------')
@bot.command() @bot.command(pass_context=True)
async def repost(url : str): async def repost(ctx, url : str):
"""Reposts an URL on SCPlanner.""" """Reposts an URL on SCPlanner."""
user = ctx.message.author
if not isinstance(user, discord.Member):
await bot.say("Please use this command in a server.")
return
if not has_role(user, config["CONFIG"]["reposters_role"]):
await bot.say("You do no have the required role.")
return
try: try:
calendar_link = auto(url) calendar_link = auto(url)
await bot.say(calendar_link) await bot.say(calendar_link)

View File

@ -1,4 +1,16 @@
[CONFIG] [CONFIG]
# do not change this
cookie_name = ci_session cookie_name = ci_session
# log in on SCPlanner, and grap the "ci_session" cookie value
cookie_value = get_your_own cookie_value = get_your_own
bot_token = get_your_own
# get one here: https://discordapp.com/developers/applications/me
bot_token = get_your_own
# reposters_role: only members of this role will be able to repost
reposters_role = reposters
[AUTOSCHEDULE]
# use_all_accounts: "yes" if you want to schedule reposts on all subs, "no" (default) if you want the bot to use your saved preferences
use_all_accounts = no