Beispiel #1
0
def printProgress():
    lingo  = duolingo.Duolingo('Strekerud')
    lingo_emil = duolingo.Duolingo('beezlebob')
    lingo_bone = duolingo.Duolingo('tandberg')
    lingo_masha = duolingo.Duolingo('Masha672543')
    lingo_sigurd = duolingo.Duolingo('sigurlu')

    language_progress = lingo.get_language_progress('ru')
    streak_info = lingo.get_streak_info()

    #print "Next level in " + str(language_progress['level_left']) + " experience"

    tenths_done = int((float(language_progress['level_progress']) / language_progress['level_points']) * 10)
    
    print "----------------------------"
    print "=== DUOLINGO STATS ==="
    print "My current streak: " + str(language_progress['streak'])
    print "Masha's streak: " + str(lingo_masha.get_language_progress('nb')['streak']) + "  (lvl: " + str(lingo_masha.get_language_progress('nb')['level']) + ")"
    print "Emil's streak: " + str(lingo_emil.get_language_progress('fr')['streak']) + "  (lvl: " + str(lingo_emil.get_language_progress('fr')['level']) + ")"
    print "Bones's streak: " + str(lingo_bone.get_language_progress('de')['streak']) + "  (lvl: " + str(lingo_bone.get_language_progress('de')['level']) + ")"
    print "Sigurd's streak: " + str(lingo_sigurd.get_language_progress('dn')['streak']) + "  (lvl: " + str(lingo_sigurd.get_language_progress('dn')['level']) + ")"
    print "Level: " + str(language_progress['level'])
    print "Level progress: [",
    for _ in range(tenths_done):
        print "#",
    for _ in range(tenths_done, 10):
        print "-",
    print "] (" + str(language_progress['level_progress']) + "/" + str(language_progress['level_points']) + ")"
    if streak_info['streak_extended_today']:
        print "Daily XP requirement IS MET."
    else:
        print "Daily XP requirement NOT MET. Fix it, Kristoffer."
    print "----------------------------"
Beispiel #2
0
async def ranking(ctx):
    global cooldownRanking
    global lingo
    if(cooldownRanking == 0):
        lingo = duolingo.Duolingo(usernameDuolingo, passwordDuolingo)
        ans = str(lingo.get_friends())
        ans = ans.replace("'", "\"")
        dic = json.loads(ans)
        dic = sorted(dic, key=lambda item: item.get("points"))
        dic.reverse()   
        embed = discord.Embed()
        embed.set_author(name="FloW")
        embed.title = "Ranking duolingo"
        i = 0
        for user in dic:
            if user["username"] != "FloWBotz":
                i += 1
                embed.add_field(name=str(i)+" - "+user["username"], value=">>> "+str(user["points"])+" xp", inline=False)
        await ctx.send(embed=embed)
        cooldownRanking = 3600
        while cooldownRanking != 0:
            cooldownRanking -= 1
            await asyncio.sleep(1)
        cooldownRanking = True
    else:
        await ctx.send("Commande en cooldown : %d s" %cooldownRanking)
Beispiel #3
0
async def dailyLeaderBoard():
    global lingo
    file = open("users.txt", mode="r")
    users = file.read()
    file.close()
    users = users.replace("'", "\"")
    usersFileDic = json.loads(users)

    lingo = duolingo.Duolingo(usernameDuolingo, passwordDuolingo)
    ans = str(lingo.get_friends())
    # ans = '[{"username": "******", "id": 670694569, "points": 7600, "languages": []}, {"username": "******", "id": 25231199, "points": 3600, "languages": []}, {"username": "******", "id": 718168090, "points": 410, "languages": []}, {"username": "******", "id": 720422604, "points": 100, "languages": []}]'
    ans = ans.replace("'", "\"")
    dic = json.loads(ans)

    for i in range(0, len(usersFileDic)):
        if(usersFileDic[i]["username"] == dic[i]["username"] and usersFileDic[i]["username"] != "FloWBotz"):
            dic[i]["points"] = dic[i]["points"] - usersFileDic[i]["points"]

    dic = sorted(dic, key=lambda item: item.get("points"))
    dic.reverse()   

    embed = discord.Embed()
    embed.set_author(name="FloW")
    embed.title = "Daily Ranking duolingo"
    i = 0
    for user in dic:
        if user["username"] != "FloWBotz":
            i += 1
            embed.add_field(name=str(i)+" - "+user["username"], value=">>> "+str(user["points"])+" xp", inline=False)
    channel = await bot.fetch_channel('797563311045869628')
    await channel.send(embed=embed)
    ans.replace("\"", "'")
    with open("users.txt", "w") as file:
        file.write(ans)
    print("daily end")
Beispiel #4
0
 def _check_duo_username(username, password):
     try:
         lingo = duolingo.Duolingo(username, password=password)
         lingo.get_friends()
         return True
     except Exception:
         return False
Beispiel #5
0
def get_vocab(language: Language,
              username: str,
              password: str,
              n_words: int = -1) -> list[str]:
    """
    Retrieves a random number of the user's current vocab words.
    Function header may be changed depending on what authentication info Duolingo needs.

    :param language: language to be fetched
    :param username: user's Duolingo username
    :param password: user's Duolingo password
    :param n_words: number of words to be returned (-1 will do all)
    :return: list of vocab words as strings
    """

    # logs into user's Duolingo account
    lingo = duolingo.Duolingo(username, password)
    my_set = lingo.get_known_words(language.code)

    # if all words are requested, they're returned as a list
    my_list = list(my_set)
    if n_words == -1:
        return my_list

    # otherwise, a random subset of the words are returned
    shuffle(my_list)
    return my_list[:n_words]
Beispiel #6
0
def update_charts():
    lingo = duolingo.Duolingo(duo_username, password=duo_pass)
    user_info = lingo.get_user_info()
    generate_chart(lingo.get_calendar(), '{}-overall.svg'.format(duo_username))
    for language in lingo.get_languages(abbreviations=True):
        print language
        filename = '{}-{}.svg'.format(duo_username, language)
        generate_chart(lingo.get_calendar(language), filename)
Beispiel #7
0
def get_words_from_API(username, password, lang):
    lingo = duolingo.Duolingo(username, password)
    vocab = lingo.get_vocabulary(language_abbr=lang)['vocab_overview']
    words = []
    for word_json_object in vocab:
        words.append(word_json_object['word_string'])
    words.sort()
    words = list(dict.fromkeys(words))  # remove duplicates
    return words
Beispiel #8
0
def scrape_duolingo():
    lingo = duolingo.Duolingo(personal.data["duoUsername"],
                              personal.data["duoPassword"])

    for lang in order:
        lang_data = lingo.get_language_details(lang)
        try:
            points[lang] = lang_data['points']
        except KeyError:
            pass
Beispiel #9
0
 def signIn(self) -> any:
     """
         Method that returns user session for duolingo user
         
     """
     try:
         self.session = duolingo.Duolingo(self.username, self.password) # stores the user credentials into the duolingo constructor
         return True # boolean value has no meaning; simply differentiate from None
     except:
         return None # used as a marker for conditional statement in the controller class methods its called from
Beispiel #10
0
def GetPoints():
    lingo = duolingo.Duolingo("osk73080", "DefaultPassword")

    data = lingo.get_leaderboard("month", time.time())
    pointsArray = []

    for item in data:
        tempDict = {}
        tempDict["Name"] = item["username"]
        tempDict["Score"] = item["points"]
        pointsArray.append(tempDict)
    return pointsArray
def streak_check():
    duo_user = config['DUOLINGO']['duo_user']
    duo_pass = config['DUOLINGO']['duo_pass']
    lingo = duolingo.Duolingo(duo_user, duo_pass)
    streak_info = lingo.get_streak_info()
    streak_value = streak_info.get('streak_extended_today')
    if streak_value != True and streak_value != False:
        print("Invalid Return")
        return streak_value
    else:
        return streak_value
        print(streak_value)
Beispiel #12
0
    def __init__(self):
        args = DuolingoNagger.parse_args(
        )[0]  # parse_known_args returns a tuple, with all the args not recognized by the current argparse
        self.duolingo_user = args.user
        self.duolingo_pass = args.password

        temp_var_nag_time = time.strptime(args.time, '%H%M')
        self.start_nagging_time = datetime.time(temp_var_nag_time.tm_hour,
                                                temp_var_nag_time.tm_min)

        self.duolingo_obj = duolingo.Duolingo(self.duolingo_user,
                                              self.duolingo_pass)
Beispiel #13
0
def get_login_data_view(request):
    username = _validate_username(request.POST.get("uname", None))
    password = request.POST.get("psw", None)
    # todo: validate

    try:
        duo.duo = duolingo.Duolingo(username, password)
    except Exception as ಠ_ಠ:
        print(ಠ_ಠ)
        # todo: return message or redirect to index

    context = {"langs": duo.duo.get_languages(abbreviations=True)}
    print(context)
    return render(request, "flashcards/select_language.html", context)
Beispiel #14
0
 def passive_trigger(self, evt):
     """
     :type evt: Event.Event
     :rtype: None
     """
     try:
         lingo = duolingo.Duolingo(self.username, password=self.password)
         friends = lingo.get_friends()
     except Exception:
         self.message_channel(
             "It seems the password no longer works for Duolingo account {}. "
             "Please reset it.".format(self.username))
         return
     result = dict()
     for friend in friends:
         result[friend["username"]] = friend["points"]
     result_str = json.dumps(result)
     d = (evt.get_send_time() - timedelta(1)).date()
     self.save_data(result, d)
     # Send date to destination
     self.message_channel(result_str)
Beispiel #15
0
import duolingo
import sys

lingo = duolingo.Duolingo(sys.argv[0])
print lingo.get_known_words('de')
Beispiel #16
0
from rest_framework.views import APIView
import inflect
import re

from django.http import HttpResponse
from rest_framework.response import Response

from ..models.mango import Mango
from ..serializers import MangoSerializer, UserSerializer

# Pull personal USERNAME and PASSWORD from .env credentials
USERNAME = os.getenv("USERNAME")
PASSWORD = os.getenv("PASSWORD")

# Sign in to duolingo API
lingo2 = duolingo.Duolingo(USERNAME, PASSWORD)
DELAY = 0.5

# Initialize engine used to pluralize words
engine = inflect.engine()


class DuoLingoAudio(APIView):
    # disable authentication for this route
    authentication_classes = []
    permission_classes = []

    def get(self, request):
        """Index request"""
        word = request.query_params.get('word')
Beispiel #17
0
class DuolingoTest(unittest.TestCase):
    lingo = duolingo.Duolingo(USERNAME, password=PASSWORD)

    def setUp(self):
        self.lang = self.lingo.user_data.learning_language

    def test_get_user_info(self):
        response = self.lingo.get_user_info()

    def test_get_settings(self):
        response = self.lingo.get_settings()

    def test_get_languages(self):
        response = self.lingo.get_languages(abbreviations=False)
        response = self.lingo.get_languages(abbreviations=True)

    def test_get_friends(self):
        response = self.lingo.get_friends()

    def test_get_calendar(self):
        response = self.lingo.get_calendar()
        response = self.lingo.get_calendar(self.lang)

    def test_get_streak_info(self):
        response = self.lingo.get_streak_info()

    def test_get_certificates(self):
        response = self.lingo.get_certificates()

    def test_get_language_details(self):
        response = self.lingo.get_language_details(self.lang)

    def test_get_language_progress(self):
        response = self.lingo.get_language_progress(self.lang)

    def test_get_known_topics(self):
        response = self.lingo.get_known_topics(self.lang)

    def test_get_known_words(self):
        response = self.lingo.get_known_words(self.lang)

    def test_get_learned_skills(self):
        response = self.lingo.get_learned_skills(self.lang)

    def test_get_language_from_abbr(self):
        response = self.lingo.get_language_from_abbr(self.lang)

    def test_get_abbreviation_of(self):
        response = self.lingo.get_abbreviation_of('portuguese')

    def test_get_activity_stream(self):
        response = self.lingo.get_activity_stream()

    def test_get_translations(self):
        response = self.lingo.get_translations('e')
        response = self.lingo.get_translations('e', self.lang)
        response = self.lingo.get_translations('e', self.lang, 'fr')
        response = self.lingo.get_translations(['e', 'a'])

    @unittest.skipIf(not PASSWORD, "You must have valid username/password")
    def test_get_leaderboard(self):
        response = self.lingo.get_leaderboard('week')
        response = self.lingo.get_leaderboard('month')

    @unittest.skipIf(not PASSWORD, "You must have valid username/password")
    def test_get_vocabulary(self):
        response = self.lingo.get_vocabulary()
        response = self.lingo.get_vocabulary(self.lang)

    @unittest.skipIf(not PASSWORD, "You must have valid username/password")
    def test_get_audio_url(self):
        response = self.lingo.get_audio_url('o')
        response = self.lingo.get_audio_url('o', self.lang)

    @unittest.skipIf(not PASSWORD, "You must have valid username/password")
    def test_get_related_words(self):
        response = self.lingo.get_related_words('o')
Beispiel #18
0
 def test_file_only_calls_login(self, mock_login, mock_data):
     duolingo.Duolingo(USERNAME, session_file="temp/filename.json")
     mock_login.assert_called_once()
     mock_data.assert_called_once()
Beispiel #19
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Jan  7 19:05:43 2020

@author: vpapg
"""


import duolingo
# https://github.com/KartikTalwar/duolingo

username = str(input("Enter your username: "******"Enter your password: "))
print('\n***** Connecting to your account...')
lingo = duolingo.Duolingo(username, password=passw)
print('***** Connection established.')

def retrieve_vocab(duolingo_account, language, filename):
    vocab = duolingo_account.get_vocabulary(language_abbr = language)
    
    skills = set()
    for skill in vocab['vocab_overview']:
        skills.update([skill['skill']])
    
    with open(filename, 'w') as f:
        for skill in skills:
            for item in vocab['vocab_overview']:
                if item['skill'] == skill:
                    f.write(str(item['word_string']) + '\t' +str(item['normalized_string'])+'\t'+str(item['skill'])+'\n')
Beispiel #20
0
# -*- coding: utf-8 -*-

import json

from flask import Flask, request
from jinja2 import Environment
from urllib.request import Request, urlopen

import duolingo
lingo = duolingo.Duolingo('Julia981676', 'xxx')
import datetime

user = '******'

app = Flask(__name__)
environment = Environment()


def jsonfilter(value):
    return json.dumps(value)


environment.filters["json"] = jsonfilter

language = list(lingo.get_user_info()["language_data"].keys())[0]
llanguage = lingo.get_language_from_abbr(language)
words = lingo.get_learned_skills(language)[-1]["words"]
languages = lingo.get_languages(abbreviations=False)

friends = ["Andrea613914", "Saga796697", "m2v9M6iB"]
friendsdict = {}
Beispiel #21
0
import duolingo
import pprint
import json

credentials = json.load(open("credentials.json", "r"))
lingo = duolingo.Duolingo(credentials["username"], credentials["password"])
response = lingo.get_lesson("Alphabet 2")
print(response)

Beispiel #22
0
 def setUp(self):
     self.lingo = duolingo.Duolingo(USERNAME, PASSWORD)
     self.lingo.set_username(USERNAME2)
     self.lang = self.lingo.user_data.learning_language
Beispiel #23
0
 def test_password_only_calls_login(self, mock_login, mock_data):
     duolingo.Duolingo(USERNAME, PASSWORD)
     mock_login.assert_called_once()
     mock_data.assert_called_once()
Beispiel #24
0
def validate_duolingo_authentication(username, password):
    try:
        duolingo.Duolingo(username, password)
    except:
        return False
    return True
Beispiel #25
0
 def login(self, password):
     try:
         self.lingo = duolingo.Duolingo(self.username, password)
         self._is_authenticated = True
     except duolingo.DuolingoException:
         print("Could not authenticate user: " + self.username)
Beispiel #26
0
import duolingo

user = duolingo.Duolingo('user ID', 'password goes here')

# prints user information

print(user.get_user_info())
print('******************************************************')

# prints user settings

print(user.get_settings())
print('******************************************************')

# prints languages learning

print(user.get_languages())
print('******************************************************')

# prints user streak info

print(user.get_streak_info())
print('******************************************************')
Beispiel #27
0
def buildDict():
    """Pull vocabulary from Duolingo account and format it into a CSV file """
    #settings for dictionary ------------------------------------
    #this determines if conjugated verbs (e.g. he drinks, you are) 
    #are part of the dictionary
    conjugations_allowed = False
    
    # Not currently used
    web_access = False
    
    
    #list of pronouns
    pronouns = {'English': ['I','you','she','he','it','we','they'],
                'French': ['je','tu','il','elle','on','nous','vous','ils','elles']}
    
    #login information for Duolingo
    username, password = fetchUserInfo()

    #native language for flashcards
    native_language = 'English'
    #log into Duolingo and create the user object
    user = duo.Duolingo(username, password)
    #get the list of languages that I'm studying
    lang_wo_abbrev = user.get_languages() #lang_wo_abbrev e.g. ['French', 'German']
    #build a dictionary linking language abbreviations (e.g. 'fr') to languages 
    #(e.g. 'French')
    lang_abbrev = {}
    for i in lang_wo_abbrev:
        lang_abbrev[i] = user.get_abbreviation_of(i)
    #lang_abbrev example = {'French':'fr', 'German':'de'}
    
    #start building a dictionary where the dict key is in the native language
    #and values are in target languages
    native_dict = {}
    #get the abbreviation of the native language, e.g. 'en' for English
    native_abbrev = user.get_abbreviation_of(native_language)
    
    #for every language, get the words that the user has learned   
    #for lang in lang_wo_abbrev:
    langlist = langs_wEnglish[1:]
    for lang in lang_abbrev.keys():
        print lang
        #make sure that we're on the right language
        #in Duolingo, the API only works with one language at a time
        #and must switch to that language before it can pull data about 
        #words, skills, etc learned in that language
        user._switch_language(lang_abbrev[lang])
        #create a temporary dict with all the words learned in this language
        temp_dict = user.get_known_words(lang_abbrev[lang])
        #now we're going to start working on the master dictionary
        #iterate through the known words for each language
        for word in temp_dict:
            #get translation, which is a dictionary entry
            #example: user.get_translations(['prynhawn'],'en','cy') returns
            #{u'prynhawn': [u'Afternoon']}
            #b/c prynhawn means afternoon in Welsh ('cy')
            translation_entry = user.get_translations([word], 
                                                      native_abbrev,
                                                      lang_abbrev[lang])
            #now we want to process the data, since a word in the native language
            #(usually English) might have multiple definitions in the 
            #target language
            key = translation_entry.keys()
            #make a list of all translations of the word
            #example: [u'Welcome', u"You're welcome", u'You are welcome'] = 
            #         translation_entry['croeso']
            native_translation = translation_entry[key[0]]
            #now we want to go through the definitions
            #if the native word is already in the dictionary, we'll just add the
            #target language translation. However, if the native word isn't in
            #the dictionary, we'll make an entry for that
            #start by iterating through the keys
            for entry in native_translation:
                #if there's an entry for the native word in the dictionary
                if entry in native_dict:
                    #if there's already an entry in this target language 
                    #in the dictionary, and we're adding a second translation 
                    #in the same target language
                    if lang in native_dict[entry]:
                        native_dict[entry][lang] += key
                    #if there's not already a translation in the target language,
                    #add one
                    else:
                        native_dict[entry][lang] += key

                #if the native word isn't in the dictionary, add it maybe
                else:
                    #see if we want to add the entry
                    if conjugations_allowed:
                        native_dict[entry][lang] = key
                    #if we're not allowing conjugations
                    else:
                        pron = pronouns[native_language]
                        c = len(pron)
                        for p in pron:
                            if str('(' + p ) in entry:
                                c = 0
                        #if there's no pronoun in the entry, add the entry
                        if c == len(pron):
                            native_dict[entry] = {}
                            native_dict[entry][lang] = key
    
    #write the data to a file called dictionary.txt in the same directory
    #as the python file, because that makes my life easier
    ctr = 0
    with open('dict.csv', 'wb') as csvfile:
        w = csv.writer(csvfile, delimiter=',')
        #write header row
        w.writerow(langs_wEnglish)
        for item in native_dict.items():
            ctr = 0
            line = ['']*(len(langlist) + 1)
            line[0] = item[0] #English
            for i in langlist:
                ctr+=1
                if(i in item[1]):
                    line[ctr] = writeMultDefs(item[1][i])
            w.writerow(line)    
    return
Beispiel #28
0
 def test_password_jwt_or_file_needed(self, mock_data):
     with self.assertRaises(duolingo.DuolingoException):
         duolingo.Duolingo(USERNAME)
     mock_data.assert_not_called()
#simple script to extract python data and write to an xlsm file
#uses openpyxl, os and of course duolingo

import openpyxl, duolingo, os
lingo = duolingo.Duolingo('tsull', 'myapipassword')
lingo.get_vocabulary()
vocab = lingo.get_vocabulary()
vocab = vocab["vocab_overview"]
workbook = openpyxl.load_workbook("Duolingo Data")
ws = workbook.active

#getting the titles
#remember structure List of Dictionarys with 14 key value pairs.
for row in ws.iter_rows(min_row=1, max_col=14, max_row=1):
    for cell in row:
        index = row.index(cell)
        columnTitle = list(vocab[0])[index]
        cell.value = columnTitle

#making a virtual table from a list of dictionaries
keyList = []
for row in ws.values:
    for value in row:
        keyList.append(value)

virTable = {}
for key in keyList:
    dataList = []
    for dictionary in vocab:
        dataList.append(dictionary[key])
    virTable[key] = dataList
Beispiel #30
0
 def test_jwt_only_calls_login(self, mock_login, mock_data):
     duolingo.Duolingo(USERNAME, jwt="jwt-example")
     mock_login.assert_called_once()
     mock_data.assert_called_once()