Example #1
0
def main():
    auth = tweepy.OAuthHandler(consumer_key, consumer_secret)
    auth.set_access_token(access_token, access_token_secret)
    api = tweepy.API(auth)
    last_id = ""
    home = str(Path.home())
    log_file = home + "/twittbot/log.txt"

    while (True):
        a = api.user_timeline(screen_name="realdonaldtrump",
                              tweet_mode='extended')
        open(log_file, 'w').close()
        print("Looking for new tweets", file=open(log_file, "a"))

        if a and a[0].id_str != last_id:
            translator = Translator()
            tweet = a[0].full_text

            print("Found Tweet: \n", tweet, file=open(log_file, "a"))
            print("---------------------------", file=open(log_file, "a"))

            # & seems to crash the translator
            tweet = tweet.replace("&", "and ")

            # Preserve the url if there is one
            index = tweet.find("http")
            url = ""
            if index != -1:
                url = tweet[index:]
                tweet = tweet[:index]

            if not tweet:
                continue
            # Translate 30 times (100 takes to long time and there is a limit on number of requests to the api)
            # Idea still the same though
            lang1, lang2 = "en", ""

            for i in range(25):
                lang2 = random.choice(list(
                    LANGUAGES.items()))[0]  # choose a random language
                tweet = translator.translate(text=tweet, src=lang1,
                                             dest=lang2).text
                lang1 = lang2

            tweet = translator.translate(
                text=tweet, src=lang1,
                dest='en').text  # translate back to english
            tweet = tweet + " " + url  # add back the url
            print("tweated: " + tweet, file=open(log_file, "a"))

            if len(tweet) + len("@realdonaldtrump ") < 280:
                api.update_status(status="@realdonaldtrump " + tweet,
                                  in_reply_to_status_id=a[0].id_str)
            else:
                api.update_status(status="@realdonaldtrump " + tweet[0:260],
                                  in_reply_to_status_id=a[0].id_str)

            last_id = a[0].id_str
            print("---------------------------", file=open(log_file, "a"))
        sleep(200)
Example #2
0
 def getLangString(self, lang):
     LANGCODES = dict(map(reversed, LANGUAGES.items()))
     simbols = list(LANGCODES.values())
     strings = list(LANGCODES.keys())
     simbolIndex = simbols.index(lang)
     langString = strings[simbolIndex]
     return langString
Example #3
0
def languages():
    """
    create a list of code languages and languages like (en : english)
    :return:
    """
    for lan, cod in LANGUAGES.items():
        print(f'{lan}: {cod} |')
Example #4
0
def show_langs():
  """
  Retorna um texto formatado mostrando todas as linguas disponíveis para tradução
  """
  texto = f"```\n{'Codigo':<8} {'Lingua'}\n" + '—' * 20 + '\n'
  for keys, values in LANGUAGES.items():
    texto += f"{keys:<8} {values}\n"
  texto += "```"
  return texto
    def initialiseWidgets(self):
        self.labelSearchResult.setHidden(True)
        self.textEditSearch.setAlignment(QtCore.Qt.AlignBottom)
        self.isShownMainTable = True
        self.buttonCheck.clicked.connect(self.buttonCheck_on_click)
        self.buttonMemory.clicked.connect(self.buttonMemory_on_click)
        self.buttonBack.clicked.connect(self.buttonBack_on_click)
        self.buttonSave.clicked.connect(self.buttonSave_on_click)
        self.buttonQuit1.clicked.connect(self.buttonQuit_on_click)
        self.buttonQuit2.clicked.connect(self.buttonQuit_on_click)
        self.textEditSearch.textChanged.connect(self.search_as_you_type)
        self.buttonTranslate.clicked.connect(self.buttonTranslate_on_click)
        self.tableWidget.itemChanged.connect(self.prepareForSaving)
        self.buttonCheck.setHidden(True)
        self.buttonSave.setHidden(True)
        self.buttonBack.setHidden(True)
        self.labelFrom.setHidden(True)
        self.labelTo.setHidden(True)
        self.comboBoxRangeStart.setHidden(True)
        self.comboBoxRangeEnd.setHidden(True)
        self.memoryMode = False
        self.resetMode = False
        self.searchMode = False
        self.langDict = dict((v.capitalize(), k) for k, v in LANGUAGES.items())
        self.comboBoxLang.addItems(self.langDict.keys())
        self.comboBoxLang.currentIndexChanged.connect(
            self.changeTranslationLang)
        self.comboBoxLang.setCurrentText('English')
        difficulties = [str(i + 1) for i in range(4)]
        self.comboBoxDifficulty.addItems(difficulties)
        self.comboBoxRangeType.addItems(['Alphabet', 'Number'])
        self.comboBoxRangeType.currentIndexChanged.connect(
            self.changeRangeType)
        self.plainTextInput.installEventFilter(self)
        self.plainTextInput.hasSelected = False
        self.comboBoxRangeStart.currentIndexChanged.connect(
            self.changeStartWord)
        self.prepareForMemoryMode()

        # note area
        self.checkBox.toggled.connect(self.checkBox_on_stateChanged)
        self.checkBox_on_stateChanged()
        self.pushButtonNoteOpen.clicked.connect(self.buttonNoteOpen_on_click)
        self.pushButtonNoteSave.clicked.connect(self.buttonNoteSave_on_click)
        self.pushButtonNoteNew.clicked.connect(self.buttonNoteNew_on_click)
        self.notePath = ''

        openAction = QtWidgets.QAction('&Open', self)
        openAction.setShortcut('Ctrl+O')
        openAction.setStatusTip('Open document')
        openAction.triggered.connect(self.fileMenuOpenAction)
        # self.checkBox.checkStateSet()
        logging.debug("intialise widgets done")
Example #6
0
def translator_function():
    from googletrans import Translator, LANGUAGES
    translator = Translator()
    final_language = session.attributes['language']
    audio_string = session.attributes['message']
    """
    Takes in audio and translates it into a new language
    
    Parameters:
    
        audio: The string which you wish to translate
        
        final_language: The language which you wish to translate to 
        
    Returns: 
    
        Translated_string: Gives back the translated string for alexa to speak back
    """
    #figures out what the origin language is
    language_initial = translator.detect(audio_string)
    #figure out the output language
    language_codes = dict(map(reversed, LANGUAGES.items()))
    final_language = final_language.lower()
    translated_language = language_codes[final_language]
    #translate the thing
    final_translate = translator.translate(audio_string,
                                           dest=translated_language,
                                           src=language_initial.lang)
    #back_language=translator.translate(final_translate.text)
    if final_translate.dest == 'it':
        output = final_translate.text
    elif final_translate.dest == 'ja':
        output = final_translate.text
    elif final_translate.dest == 'de':
        output = final_translate.text
    elif final_translate.dest == 'fr':
        output = final_translate.text
    elif final_translate.dest == 'es':
        output = final_translate.text
    else:
        translation = []
        audio_string_list = audio_string.split()
        for i in range(len(audio_string_list)):
            final_translate = translator.translate(audio_string_list[i],
                                                   dest=translated_language,
                                                   src=language_initial.lang)
            if final_translate.pronunciation is None:
                translation.append(final_translate.text)
            else:
                translation.append(final_translate.pronunciation)
        output = " ".join(translation)
    return output
Example #7
0
    def translate(self, text, dest_lang):
        if dest_lang.lower() not in LANGUAGES.values():
            raise ValueError("Selected language is not supported!")

        dest_lang_tag = [
            lang_tag for lang_tag, lang in LANGUAGES.items()
            if lang == dest_lang
        ][0]

        translation = self.translator.translate(text,
                                                src='en',
                                                dest=dest_lang_tag)
        return translation
Example #8
0
def list_of_langs():
    output = "Список всех кодов и соответствующих им языков:\n"

    for key, value in LANGUAGES.items():
        output = output + key + " - " + value + "\n"

    output = output + "\nСписок всех доступных раскладок клавиатуры: "

    for key, value in layouts.items():
        output = output + key + " "

    try:
        file = open("langlist.txt", "w")
        file.write(output)
        file.close()
        logger.write_log("INFO: langlist updated successful")
    except Exception as e:
        logger.write_log("ERR: langlist file isn't available")
        logger.write_log("ERR: " + str(e) + "\n" + traceback.format_exc())
Example #9
0
    async def lang(self, ctx: commands.Context):
        langs = {}
        i = 0
        taille = 0
        for key, value in LANGUAGES.items():
            languages = f"**`{key}`**: *{value}*"
            taille += len(languages)
            if taille > 1300:
                i += 1
                taille = 0

            if not i in langs:
                langs[i] = []

            langs[i].append(languages)

        await ctx.author.send("**Voici la liste de toutes les langues disponibles:**")
        for j in range(i+1):
            await ctx.author.send("\n".join(langs[j]))

        await ctx.author.send(f"__**Veuillez utiliser l'abréviation pour traduire une phrase dans le serveur.**__ Par exemple pour traduire 'Bonjour' en anglais je vais écrire `{ctx.prefix}{self.translate.name} en Bonjour` et la phrase sera traduite en anglais.")
Example #10
0
    def setup_headerbar(self):
        # Connect history buttons
        self.return_btn.connect('clicked', self.ui_return)
        self.forward_btn.connect('clicked', self.ui_forward)

        # Left lang selector
        self.src_lang_selector = DialectLangSelector()
        self.src_lang_selector.connect('notify::selected',
                                       self.on_src_lang_changed)
        # Set popover selector to button
        self.src_lang_btn.set_popover(self.src_lang_selector)
        self.src_lang_selector.set_relative_to(self.src_lang_btn)

        # Right lang selector
        self.dest_lang_selector = DialectLangSelector()
        self.dest_lang_selector.connect('notify::selected',
                                        self.on_dest_lang_changed)
        # Set popover selector to button
        self.dest_lang_btn.set_popover(self.dest_lang_selector)
        self.dest_lang_selector.set_relative_to(self.dest_lang_btn)

        # Add languages to both list
        for code, name in LANGUAGES.items():
            self.src_lang_selector.insert(code, name.capitalize())
            self.dest_lang_selector.insert(code, name.capitalize())

        self.langs_button_box.set_homogeneous(False)

        # Switch button
        self.switch_btn.connect('clicked', self.ui_switch)

        # Add menu to menu button
        builder = Gtk.Builder.new_from_resource(f'{RES_PATH}/menu.ui')
        menu = builder.get_object('app-menu')
        menu_popover = Gtk.Popover.new_from_model(self.menu_btn, menu)
        self.menu_btn.set_popover(menu_popover)
Example #11
0
import speech_recognition as sr
import pyttsx3
import sys
from googletrans import Translator, LANGUAGES

tts = pyttsx3.init()
translator = Translator()

langOptions = dict(map(reversed, LANGUAGES.items()))

# Modifying some of the keys/values because tts makes these difficult to select or repeats
del langOptions[
    "Filipino"]  #Filipino had two keys so removed the capitalized version
del langOptions["chinese (simplified)"]
langOptions["chinese simplified"] = "zh-cn"
del langOptions["chinese (traditional)"]
langOptions["chinese traditional"] = "zh-tw"
del langOptions["myanmar (burmese)"]
langOptions["myanmar"] = "my"
del langOptions["Hebrew"]
langOptions["hebrew"] = "he"
del langOptions["kurdish (kurmanji)"]
langOptions["kurdish"] = "ku"


def speak(tts, text):
    tts.say(text)
    tts.runAndWait()


def listLanguages():
Example #12
0
#!/bin/env python3

## All data is derived from distrowatch.com and wikipedia.

from googletrans import Translator, LANGUAGES
import json

LANGFOLDER = ""
t = Translator()
#for key in LANGUAGES:
#    print(key, "->", LANGUAGES[key])
lcount = 0
for item in LANGUAGES.items():
    lcount += 1
    with open(LANGFOLDER + 'base.json') as JSONfile:
        DATA = json.load(JSONfile)
    print(f"Translating NEOS Language File to {item[0]}.")
    DATA["localeCode"] = item[0]
    kcount = 0
    for key in DATA["messages"].items():
        kcount += 1
        if key[1] != "":
            DATA["messages"][key[0]] = t.translate(key[1],
                                                   src='en',
                                                   dest=item[0]).text
            if DATA["messages"][key[0]] != key[1]:
                print(
                    f"[{item[0]} {lcount}/{len(LANGUAGES.items())} {kcount}/{len(DATA['messages'].items())}] {key[0]}: {key[1]} -> \33[1;32m{DATA['messages'][key[0]]}\33[m"
                )
            else:
                print(
Example #13
0
def get_key(val):
    for key, value in LANGUAGES.items():
        if val == value:
            return key
    return "language key doesn't exist"
Example #14
0
def codes_viewer():
    for k, v in LANGUAGES.items():
        print(
            f'{Colors.OKGREEN} Initials: {Colors.FAIL}{k}\t{Colors.OKGREEN}Language: {Colors.FAIL}{v} {Colors.ENDC}'
        )
Example #15
0
async def on_message(message):

    #Greetings and Cookies and Random Stuff

    if message.content.upper().startswith('HELLO!'):
        userID = message.author.id
        await client.send_message(message.channel, "Hello <@%s>!" % (userID))
    if message.content.upper().startswith('YO!'):
        userID = message.author.id
        await client.send_message(message.channel,
                                  "Yo to you too, <@%s>!" % (userID))
    if message.content.upper().startswith('WAZZ POPPIN!'):
        userID = message.author.id
        await client.send_message(message.channel,
                                  "Not much, <@%s>!" % (userID))
    if message.content.upper().startswith('COOKIE!'):
        cookies = [
            'choco chip', 'vanilla', 'caramel', 'butterscotch', 'almond',
            'chunky coconut', 'marmalade', 'choco lava', 'butter'
        ]
        index_cookie = random.randint(0, len(cookies) - 1)
        cookie_send = cookies[index_cookie]
        cookie_message = '{} , {} gave you a nice {} cookie :cookie: !'.format(
            message.content.split(' ')[1], message.author.mention, cookie_send)
        await client.send_message(message.channel, cookie_message)

    #Movies,TV Series and Video Games plot summaries

    if message.content.upper().startswith('MOVIE!'):
        userID = message.author.id
        args = message.content.split(" ")
        moviename = " ".join(args[1:])
        movie = ia.search_movie(moviename)
        movie1 = movie[0]
        movieid = ia.get_imdbID(movie1)
        movieinfo = ia.get_movie(movieid)
        plot = movieinfo['plot'][0]
        embed = discord.Embed(title='PLOT SUMMARY',
                              description='',
                              colour=discord.Colour.teal())
        embed.add_field(name=moviename, value=plot, inline=False)
        await client.send_message(message.channel, embed=embed)

    #Wikipedia Search

    if message.content.upper().startswith('WIKI!'):
        args = message.content.split(" ")
        item_search_title = " ".join(args[1:])
        item_summary = wk.summary(item_search_title, sentences=4)
        embed = discord.Embed(title='Wikipedia Summary',
                              description='',
                              colour=discord.Colour.teal())
        embed.add_field(name=item_search_title.capitalize(),
                        value=item_summary,
                        inline=False)
        await client.send_message(message.channel, embed=embed)

    #Server Info

    # 1.) Roles information

    if message.content.upper().startswith('ROLES!'):
        server = client.get_server(os.getenv('SERVER_ID'))
        roles_list = server.role_hierarchy
        for role in roles_list:
            if not role.is_everyone:
                embed = discord.Embed(title=role.name,
                                      description='',
                                      colour=role.colour)
                await client.send_message(message.channel, embed=embed)

    # 2.) Server information

    if message.content.upper().startswith('INFO!'):
        server = client.get_server(os.getenv('SERVER_ID'))
        people_count = server.member_count
        time_of_creation = server.created_at
        owner_name = server.owner.name
        icon = server.icon_url
        embed = discord.Embed(title=server.name,
                              description='SERVER INFO',
                              colour=discord.Colour.teal())
        embed.set_thumbnail(url=icon)
        embed.add_field(name='Member count:',
                        value='Humans : {}\nBots : 1'.format(people_count - 1),
                        inline=False)
        embed.add_field(name='Time of Origin:',
                        value='{}-{}-{}'.format(time_of_creation.day,
                                                time_of_creation.month,
                                                time_of_creation.year),
                        inline=False)
        embed.add_field(name='Owner:', value=owner_name, inline=False)
        await client.send_message(message.channel, embed=embed)

    # 3.) Bar Plot depicting statuses of people

    if message.content.upper().startswith("STATUS!"):
        server = client.get_server(os.getenv('SERVER_ID'))
        if os.path.isfile('stats.png') == "True":
            os.remove("stats.png")
        mem_list = server.members
        online = 0
        offline = 0
        idle = 0
        do_not_disturb = 0
        invisible = 0
        for mem in mem_list:
            if str(mem.status) == "online":
                online += 1
            elif str(mem.status) == "offline":
                offline += 1
            elif str(mem.status) == "idle":
                idle += 1
            elif str(mem.status) == "dnd":
                do_not_disturb += 1
            else:
                invisible += 1
        stats = ('Online', 'Offline', 'Idle', 'Do Not Disturb')
        y_pos = np.arange(len(stats))
        status_mems = [online, offline, idle, do_not_disturb]
        plt.bar(y_pos,
                status_mems,
                align='center',
                alpha=0.5,
                color=['green', 'grey', 'yellow', 'red'])
        plt.xticks(y_pos, stats)
        plt.yticks(np.arange(0, len((mem_list)), step=1))
        plt.ylabel('Members')
        plt.title('Status Statistics')
        plt.savefig('stats.png')
        await client.send_file(message.channel, 'stats.png')
        plt.clf()

    #Moderation Commands

    # 1.) Kick a user
    if message.content.upper().startswith("KICK!"):
        server = client.get_server(os.getenv('SERVER_ID'))
        flag = False
        if message.author.server_permissions.kick_members == True and message.author.server_permissions.ban_members == True:
            flag = True
        if flag == True:
            for mem_ber in server.members:
                if mem_ber.mentioned_in(message) == True:
                    await client.kick(mem_ber)
                    embed = discord.Embed(
                        title='Kicked',
                        description="{} has been kicked from the server".
                        format(mem_ber.mention),
                        colour=discord.Colour.red())
                    await client.send_message(message.channel, embed=embed)
                    break

        else:
            embed = discord.Embed(
                title='Warning',
                description='{} You are not allowed to use this command!'.
                format(message.author.mention),
                colour=discord.Colour.red())
            await client.send_message(message.channel, embed=embed)
    # 2.) Ban a user
    if message.content.upper().startswith("BAN!"):
        server = client.get_server(os.getenv('SERVER_ID'))
        flag = False
        if message.author.server_permissions.kick_members == True and message.author.server_permissions.ban_members == True:
            flag = True
        if flag == True:
            for mem_ber in server.members:
                if mem_ber.mentioned_in(message) == True:
                    await client.ban(mem_ber, 0)
                    embed = discord.Embed(
                        title='Banned',
                        description="{} has been banned from the server".
                        format(mem_ber.mention),
                        colour=discord.Colour.red())
                    await client.send_message(message.channel, embed=embed)
                    break

        else:
            embed = discord.Embed(
                title='Warning',
                description='{} You are not allowed to use this command!'.
                format(message.author.mention),
                colour=discord.Colour.red())
            await client.send_message(message.channel, embed=embed)

    #Bot Commands Help

    if message.content.upper().startswith('HELP!'):
        embed = discord.Embed(
            title='SPARKY TO YOUR RESCUE!',
            description=
            'COMMANDS [Note that the commands are case insensitive.] -->',
            colour=discord.Colour.teal())
        embed.add_field(name='help!', value='Gives this list', inline=False)
        embed.add_field(name='psrules!',
                        value='Rules of Practice Sessions',
                        inline=False)
        embed.add_field(name='modhelp!',
                        value='Moderation Commands',
                        inline=False)
        embed.add_field(name='translatehelp!',
                        value='Translation Commands',
                        inline=False)
        embed.add_field(name='lrhelp!',
                        value='Language Based Roles Commands',
                        inline=False)
        embed.add_field(name='calchelp!',
                        value='Calculator Commands',
                        inline=False)
        embed.add_field(name='servhelp!',
                        value='Server Commands',
                        inline=False)
        embed.add_field(name='funhelp!', value='Fun Commands', inline=False)
        embed.add_field(name='utilhelp!',
                        value='General Utility Commands help',
                        inline=False)
        await client.send_message(message.channel, embed=embed)

    # General Utility Commands

    if message.content.upper().startswith('UTILHELP!'):
        embed = discord.Embed(
            title='General Utility Help',
            description=
            'General Commands that dont belong in any other categories',
            colour=discord.Color.dark_grey())
        embed.add_field(name='stackov! Query',
                        value='Search for solutions to programming doubts.',
                        inline=False)
        embed.add_field(name='embed! text to be embedded',
                        value='Embeds text.',
                        inline=False)
        await client.send_message(message.channel, embed=embed)

    #Server Related Commands

    if message.content.upper().startswith('SERVHELP!'):
        embed = discord.Embed(
            title='Server Commands',
            description=
            'COMMANDS [Note that the commands are case insensitive.] -->',
            colour=discord.Colour.gold())
        embed.add_field(name='roles!',
                        value='Gives all the roles present in the server.',
                        inline=False)
        embed.add_field(name='info!', value='Gives server info.', inline=False)
        embed.add_field(
            name='status!',
            value=
            'Gives a plot depicting the statuses of people on the server.',
            inline=False)
        embed.add_field(name='profile!',
                        value='Check out your profile card.',
                        inline=False)
        embed.add_field(name='profile mention member!',
                        value='Check out profile card of any member.',
                        inline=False)
        embed.add_field(name='ping!', value='Ping Sparky.', inline=False)
        await client.send_message(message.channel, embed=embed)

    #Fun Commands

    if message.content.upper().startswith('FUNHELP!'):
        embed = discord.Embed(
            title='Fun Commands',
            description=
            'COMMANDS [Note that the commands are case insensitive.] -->',
            colour=discord.Colour.magenta())
        embed.add_field(
            name='wiki!',
            value='Gives brief summary from Wikipedia of the queried item',
            inline=False)
        embed.add_field(name='coin! type heads or tails',
                        value='Make Sparky toss a coin and see if you win',
                        inline=False)
        embed.add_field(name='slot!',
                        value='Test your luck on Sparky\'s slot machine!',
                        inline=False)
        embed.add_field(name='joke!',
                        value='Cheeky and nerdy Chuck Norris jokes',
                        inline=False)
        embed.add_field(
            name='movie! name of Movie / TV Series /  Video Game',
            value='Gives the plot summary of the Movie/ TV series / Video Game',
            inline=False)
        embed.add_field(name='hello! / yo! / wazz poppin!',
                        value='Sparky says hi to you',
                        inline=False)
        embed.add_field(name='cookie! mention user',
                        value='Give someone a delicious cookie',
                        inline=False)
        embed.add_field(name='sparkygif! gif topic',
                        value='Posts a GIF on the mentioned topic',
                        inline=False)
        embed.add_field(name='poll! item1-without-spaces item2-without-spaces',
                        value='Creates a 2 item poll',
                        inline=False)
        embed.add_field(name='trivia!',
                        value='Answer Sparky\'s CS trivia questions!',
                        inline=False)
        await client.send_message(message.channel, embed=embed)

    #MOD Commands Help

    if message.content.upper().startswith('MODHELP!'):
        if message.author.server_permissions.kick_members == True and message.author.server_permissions.ban_members == True:
            embed = discord.Embed(title='MOD COMMANDS',
                                  description='Can be used only by Admins.',
                                  colour=discord.Colour.red())
            embed.add_field(name='purge! number of messages',
                            value='Purges through a given number of messages.',
                            inline=False)
            embed.add_field(name='kick! user',
                            value='Kicks the mentioned user from the server.',
                            inline=False)
            embed.add_field(name='ban! user',
                            value='Bans the mentioned user from the server.',
                            inline=False)
            await client.send_message(message.channel, embed=embed)
        else:
            embed = discord.Embed(
                title='Warning',
                description='{} You are not allowed to use this command!'.
                format(message.author.mention),
                colour=discord.Colour.red())
            await client.send_message(message.channel, embed=embed)

    #Practice Session Rules

    if message.content.upper().startswith('PSRULES!'):
        channel_CP = client.get_channel(os.getenv('CP_CHANNEL_ID'))
        role_id_list = []
        for role in message.server.roles:
            if role.name.upper() == 'PROGRAMMERS':
                role_id_list.append(role.mention)
            if role.name.upper() == 'CODERS':
                role_id_list.append(role.mention)
        embed = discord.Embed(
            title='Practice Session Rules',
            description='To be followed by everyone who is participating',
            colour=discord.Colour.red())
        embed.add_field(
            name='Rule-1',
            value='Post your solutions in {} using appropriate discord markdown.'
            .format(channel_CP),
            inline='False')
        embed.add_field(
            name='Rule-2',
            value=
            'If you have a doubt, ping anyone of the support staff mentioned below. Don\'t ping the entire role',
            inline='False')
        embed.add_field(
            name='Rule-3',
            value=
            'Try to make your code as efficient as possible. If you don\'t know about efficiency, leave this point.',
            inline='False')
        embed.add_field(name='Rule-4',
                        value='Do not cheat or copy.',
                        inline='False')
        embed.add_field(
            name='Rule-5',
            value=
            'Use logic along with the in-built functions to get the most output.',
            inline='False')
        embed.add_field(
            name='Rule-6',
            value=
            'Use C++ / C /Python / Java. If you feel excited, use Haskell or Erlang at your own risk.',
            inline='False')
        embed.add_field(
            name='Link for Discord Markup',
            value=
            'https://support.discordapp.com/hc/en-us/articles/210298617-Markdown-Text-101-Chat-Formatting-Bold-Italic-Underline-',
            inline='False')
        embed.add_field(name='Support Staff',
                        value=role_id_list[0] + '\n' + role_id_list[1],
                        inline='False')
        await client.send_message(message.channel, embed=embed)
    #PING

    if message.content.upper().startswith('PING!'):
        start = time.time() * 1000
        msg = await client.send_message(message.channel, 'PONG! :ping_pong:')
        end = time.time() * 1000
        await client.edit_message(message=msg,
                                  new_content=':ping_pong: `{} ms`'.format(
                                      '{0:.3f}'.format(end - start)))

    #Coin Flip Game
    if message.content.upper().startswith('COIN!'):
        args = message.content.split(" ")
        result_list = ["Heads", "Tails"]
        choice = random.randint(0, 1)
        if args[1].upper() == result_list[choice].upper():
            result = "{} it is! You win!".format(result_list[choice])
            embed = discord.Embed(title='Coin Flip',
                                  description=result,
                                  colour=discord.Colour.teal())
            await client.send_message(message.channel, embed=embed)
        else:
            result = " Uh oh, its {}! Better luck next time!".format(
                result_list[choice])
            embed = discord.Embed(title='Coin Flip',
                                  description=result,
                                  colour=discord.Colour.teal())
            await client.send_message(message.channel, embed=embed)

    #Slot Machine Game
    if message.content.upper().startswith('SLOT!'):
        result_list = [':apple:', ':pear:', ':tangerine:']
        result_list2 = [':grapes:', ':strawberry:', ':cherries:']
        result_list3 = [':hotdog:', ':icecream:', ':taco:']
        choice1 = random.randint(0, 2)
        choice2 = random.randint(0, 2)
        choice3 = random.randint(0, 2)
        e11 = result_list[choice1]
        e12 = result_list[choice2]
        e13 = result_list[choice3]
        e21 = result_list2[choice1]
        e22 = result_list2[choice2]
        e23 = result_list2[choice3]
        e31 = result_list3[choice1]
        e32 = result_list3[choice2]
        e33 = result_list3[choice3]
        result = e11 + " | " + e12 + " | " + e13 + "\n" + e21 + " | " + e22 + " | " + e23 + "\n" + e31 + " | " + e32 + " | " + e33
        row1 = False
        row2 = False
        row3 = False
        row_count = 0
        if (e11 == e12) and (e12 == e13) and (e13 == e11):
            row1 = True
            row_count += 1
        if (e21 == e22) and (e22 == e23) and (e23 == e21):
            row2 = True
            row_count += 1
        if (e31 == e32) and (e32 == e33) and (e33 == e31):
            row3 = True
            row_count += 1
        if row_count == 0:
            res_mes = "Better luck next time!"
        if row_count == 1:
            res_mes = "You got 1 row! Nice work!"
        if row_count == 2:
            res_mes = "You got 2 rows! Awesome!"
        if row_count == 3:
            res_mes = "Hattrick!"
        embed = discord.Embed(title='Slot Machine',
                              description=result,
                              colour=discord.Colour.teal())
        embed.add_field(name='Result', value=res_mes, inline=False)
        await client.send_message(message.channel, embed=embed)

    #Joke

    if message.content.upper().startswith('JOKE!'):
        l = requests.get('http://api.icndb.com/jokes/random?limitTo=[nerdy]')
        l.text.split(' ')
        joke = eval(l.text)['value']['joke']
        embed = discord.Embed(title='Joke',
                              description=joke,
                              colour=discord.Colour.blue())
        await client.send_message(message.channel, embed=embed)

    #Purge Deleting Messages

    if message.content.upper().startswith('PURGE!'):
        flag = False
        if message.author.server_permissions.kick_members == True and message.author.server_permissions.ban_members == True:
            flag = True
        if flag == True:
            args = int(message.content.split(' ')[1])
            print(args)
            await client.purge_from(message.channel, limit=args)
        else:
            embed = discord.Embed(
                title="Warning!",
                description='You are not allowed to use this command',
                colour=discord.Colour.red())
            await client.send_message(message.channel, embed=embed)

    #Language Based Roles Help

    if message.content.upper().startswith('LRHELP!'):
        embed = discord.Embed(title='Language Based Roles Help',
                              description='C/C++/Java/Python',
                              colour=discord.Colour.purple())
        embed.add_field(name='LANGROLE! name of role from above 4',
                        value='Adds the role',
                        inline=False)
        embed.add_field(name='LANGROLEREMOVE! removes role from above 4',
                        value='Removes the role',
                        inline=False)
        await client.send_message(message.channel, embed=embed)

    #Add Language Based Roles

    if message.content.upper().startswith('LANGROLE!'):
        lang_role_channel = client.get_channel(os.getenv('LANG_ROLE_ID'))
        if message.channel.id == lang_role_channel.id:
            arg = message.content.split(' ')[1]
            server = client.get_server(os.getenv('SERVER_ID'))
            role_member = None
            if arg.upper() == 'C++' or arg.upper() == 'PYTHON' or arg.upper(
            ) == 'C' or arg.upper() == 'JAVA':
                for role in server.roles:
                    if role.name.upper() == arg.upper():
                        await client.add_roles(message.author, role)
                        role_member = role
                        break
                await client.delete_message(message)
                embed = discord.Embed(
                    title=message.author.name,
                    description='You have been alloted the {} role!'.format(
                        role_member.mention),
                    colour=role_member.colour)
                await client.send_message(message.channel, embed=embed)
            else:
                embed = discord.Embed(
                    title='WARNING',
                    description='You are not allowed to add this role.',
                    colour=discord.Colour.red())
                await client.send_message(message.channel, embed=embed)
        else:
            embed = discord.Embed(
                title='Warning',
                description='You can use this command only in {}'.format(
                    lang_role_channel.mention),
                colour=discord.Colour.red())
            await client.send_message(message.channel, embed=embed)

    #Remove Language Based Roles

    if message.content.upper().startswith('LANGROLEREMOVE!'):
        lang_role_channel = client.get_channel(os.getenv('LANG_ROLE_ID'))
        if message.channel.id == lang_role_channel.id:
            arg = message.content.split(' ')[1]
            server = client.get_server(os.getenv('SERVER_ID'))
            role_member = None
            if arg.upper() == 'C++' or arg.upper() == 'PYTHON' or arg.upper(
            ) == 'C' or arg.upper() == 'JAVA':
                for role in server.roles:
                    if role.name.upper() == arg.upper():
                        await client.remove_roles(message.author, role)
                        role_member = role
                        break
                await client.delete_message(message)
                embed = discord.Embed(
                    title=message.author.name,
                    description='You have removed the {} role!'.format(
                        role_member.mention),
                    colour=role_member.colour)
                await client.send_message(message.channel, embed=embed)
            else:
                embed = discord.Embed(
                    title='WARNING',
                    description='You are not allowed to remove this role.',
                    colour=discord.Colour.red())
                await client.send_message(message.channel, embed=embed)
        else:
            embed = discord.Embed(
                title='Warning',
                description='You can use this command only in {}'.format(
                    lang_role_channel.mention),
                colour=discord.Colour.red())
            await client.send_message(message.channel, embed=embed)

    #GIFs

    if message.content.upper().startswith('SPARKYGIF!'):
        g = safygiphy.Giphy()
        target = message.content.split(' ')[1]
        gif = g.random(tag=target)['data']['url']
        await client.send_message(message.channel, gif)

    #Profile

    if message.content.upper().startswith('PROFILE!'):
        server = client.get_server(os.getenv('SERVER_ID'))
        if message.content.upper() == "PROFILE!":
            name = message.author.name
            pfp = message.author.avatar_url
            joindate = message.author.joined_at
            roles = message.author.roles
            string = []
            for item in roles:
                if item.name != '@everyone':
                    string.append(item.mention)
            string = list(reversed(string))
            string = '  '.join(string)
            embed = discord.Embed(title='PROFILE',
                                  description=server.name.upper(),
                                  colour=discord.Colour.teal())
            embed.set_thumbnail(url=pfp)
            embed.add_field(name='Name:', value=name, inline='False')
            embed.add_field(name='Joined the server on:',
                            value='{}-{}-{}'.format(joindate.day,
                                                    joindate.month,
                                                    joindate.year),
                            inline='False')
            embed.add_field(name='Roles:', value=string, inline='False')
            await client.send_message(message.channel, embed=embed)
        else:
            for mem in server.members:
                if mem.mentioned_in(message) == True:
                    name = mem.name
                    pfp = mem.avatar_url
                    joindate = mem.joined_at
                    roles = mem.roles
                    string = []
                    for item in roles:
                        if item.name != '@everyone':
                            string.append(item.mention)
                    string = list(reversed(string))
                    string = '  '.join(string)
                    embed = discord.Embed(title='PROFILE',
                                          description=server.name.upper(),
                                          colour=discord.Colour.teal())
                    embed.set_thumbnail(url=pfp)
                    embed.add_field(name='Name:', value=name, inline='False')
                    embed.add_field(name='Joined the server on:',
                                    value='{}-{}-{}'.format(
                                        joindate.day, joindate.month,
                                        joindate.year),
                                    inline='False')
                    embed.add_field(name='Roles:',
                                    value=string,
                                    inline='False')
                    await client.send_message(message.channel, embed=embed)
                    break
    #Translate Commands

    if message.content.upper().startswith('TRANSLATE!'):
        args = ' '.join(message.content.split(' ')[2::])
        lang = message.content.split(' ')[1]
        translations = translator.translate(args, dest=lang)
        embed = discord.Embed(title='SPARKY TRANSLATE',
                              description='Sparky Translates for you!',
                              colour=discord.Colour.teal())
        embed.add_field(name='Original Message:', value=args, inline='False')
        embed.add_field(name='Translated Message:',
                        value=translations.text,
                        inline='False')
        await client.send_message(message.channel, embed=embed)

    if message.content.upper().startswith('TRANSLATELANGS!'):
        msg = dict(map(reversed, LANGUAGES.items()))
        args = message.content.split(' ')[1]
        languages = list(msg.keys())
        if args.lower() in languages:
            embed = discord.Embed(title=args.lower(),
                                  description='The Code is: {}'.format(
                                      msg[args.lower()]),
                                  colour=discord.Colour.teal())
            await client.send_message(message.channel, embed=embed)
        else:
            embed = discord.Embed(title='Warning!',
                                  description='This language is not available',
                                  colour=discord.Colour.teal())
            await client.send_message(message.channel, embed=embed)

    if message.content.upper().startswith('TRANSLATEHELP!'):
        embed = discord.Embed(title='Sparky Translation Help',
                              description='Commands',
                              colour=discord.Colour.teal())
        embed.add_field(name='translatelangs! language',
                        value='Gives the code of the language asked',
                        inline='False')
        embed.add_field(
            name='translate! languagecode message to be translated',
            value='Translates the given message into the selected language.',
            inline='False')
        await client.send_message(message.channel, embed=embed)

    #Calculator

    if message.content.upper().startswith('CALC!'):
        args = message.content.split(' ')
        res = 0
        if args[1].upper() == 'SIN':
            res = math.sin(math.radians(float(args[2])))
        elif args[1].upper() == 'COS':
            res = math.cos(math.radians(float(args[2])))
        elif args[1].upper() == 'TAN':
            res = math.tan(math.radians(float(args[2])))
        elif args[1].upper() == 'EXP':
            res = math.exp(float(args[2]))
        elif args[1].upper() == 'POW':
            res = math.pow(float(args[2]), float(args[3]))
        elif args[1].upper() == 'SQRT':
            if float(args[2]) >= 0:
                res = math.sqrt(float(args[2]))
            else:
                res = "Mathematical Error!"
        elif args[1].upper() == 'LOG':
            if float(args[2]) > 0 and float(args[3]) > 0:
                res = math.log(float(args[2]), float(args[3]))
            else:
                res = "Mathematical Error!"
        elif args[1].upper() == 'EVAL':
            s = ''.join(args[2:])
            res = eval(s)
        else:
            res = 'Wrong Command!'
        embed = discord.Embed(title='Sparky\'s Calculator',
                              description='Answer',
                              colour=discord.Colour.orange())
        embed.add_field(name=' '.join(args[1:]), value=res, inline='False')
        await client.send_message(message.channel, embed=embed)

    if message.content.upper().startswith('CALCHELP!'):
        embed = discord.Embed(title='Sparky\'s Calculator',
                              description='Quick Maths',
                              colour=discord.Colour.orange())
        embed.add_field(name='calc! sin/cos/tan angle',
                        value='Sine/Cosine/Tangent of the given angle',
                        inline='False')
        embed.add_field(name='calc! exp number',
                        value='Exp(number)',
                        inline='False')
        embed.add_field(name='calc! log value base',
                        value='Log of value to the given base',
                        inline='False')
        embed.add_field(name='calc! sqrt number',
                        value='Square root of number',
                        inline='False')
        embed.add_field(name='calc! pow number exponent',
                        value='Value of number raised to exponent',
                        inline='False')
        embed.add_field(name='calc! eval expression_without_spaces',
                        value='Value of the expression',
                        inline='False')
        await client.send_message(message.channel, embed=embed)

    #Poll

    if message.content.upper().startswith('POLL!'):
        args = message.content.split(' ')[1:]
        item1 = args[0]
        item2 = args[1]
        embed = discord.Embed(
            title='POLL',
            description='A poll has been created by {}!'.format(
                message.author.mention),
            colour=discord.Colour.blue())
        embed.add_field(name=':one: {}'.format(item1.upper()),
                        value='React with :one: to vote',
                        inline=False)
        embed.add_field(name=':two: {}'.format(item2.upper()),
                        value='React with :two: to vote',
                        inline=False)
        msg = await client.send_message(message.channel, embed=embed)
        await client.add_reaction(msg, '\U00000031\U000020e3')
        await client.add_reaction(msg, '\U00000032\U000020e3')

    # Stackoverflow Search

    if message.content.upper().startswith('STACKOV!'):
        args = ' '.join(message.content.split(' ')[1:])
        query = search('Stackoverflow ' + args)
        embed = discord.Embed(title='StackOverflow Search',
                              description='Results for the query',
                              colour=discord.Color.orange())
        print('Stackoverflow ' + args)
        for item in query:
            embed.add_field(name='-->', value=item, inline=False)
        await client.send_message(message.channel, embed=embed)

    # Embed Text

    if message.content.upper().startswith('EMBED!'):
        args = ' '.join(message.content.split(' ')[1:])
        embed = discord.Embed(title='Embedded by {}'.format(
            message.author.name),
                              description=args,
                              colour=discord.Color.dark_orange())
        await client.send_message(message.channel, embed=embed)

    #Trivia

    if message.content.upper().startswith("TRIVIA!"):
        req = requests.get(
            "https://opentdb.com/api.php?amount=1&category=18&type=multiple")
        texts = ast.literal_eval(req.text)
        question = texts["results"][0]["question"]
        cor_ans = texts["results"][0]["correct_answer"]
        incorrect_answers = texts["results"][0]["incorrect_answers"]
        incorrect_answers.append(cor_ans)
        answers_lis = incorrect_answers
        random.shuffle(answers_lis)
        embed = discord.Embed(
            title="CS TRIVIA by Sparky",
            description="Type a number between 1 and 4 to choose your answer.",
            colour=discord.Color.dark_teal())
        embed.add_field(name='Question', value=question, inline=False)
        embed.add_field(name=':one:', value=answers_lis[0], inline=False)
        embed.add_field(name=':two:', value=answers_lis[1], inline=False)
        embed.add_field(name=':three:', value=answers_lis[2], inline=False)
        embed.add_field(name=':four:', value=answers_lis[3], inline=False)
        await client.send_message(message.channel, embed=embed)
        msg = await client.wait_for_message(author=message.author,
                                            channel=message.channel)
        options = ["1", "2", "3", "4"]
        if msg.content in options:
            if answers_lis[int(msg.content) - 1] == cor_ans:
                embed = discord.Embed(
                    title="Correct Answer!",
                    description=
                    "{} has answered the question correctly, the answer is Option-{} : {}!"
                    .format(message.author.name, msg.content, cor_ans),
                    colour=discord.Color.green())
                await client.send_message(message.channel, embed=embed)
            else:
                embed = discord.Embed(
                    title="Wrong Answer!",
                    description=
                    "{} has answered the question wrong, the correct answer is Option-{} : {}!"
                    .format(message.author.name,
                            answers_lis.index(cor_ans) + 1, cor_ans),
                    colour=discord.Color.red())
                await client.send_message(message.channel, embed=embed)
        else:
            embed = discord.Embed(
                title="Warning!",
                description=
                "Type a number between 1 and 4 only (both inclusive)!",
                colour=discord.Color.red())
            await client.send_message(message.channel, embed=embed)
Example #16
0
def get_languagecode(lang):
    for k, v in LANGUAGES.items():
        if v == lang.lower():
            return k
    return 0
Example #17
0
def codes(code_lang: str):
    for code, lang in LANGUAGES.items():
        if code == code_lang:
            return True
    return False
Example #18
0
from googletrans import LANGUAGES
from django.db import models

language_choices = []
for key, value in LANGUAGES.items():
    language_choices.append((key, value.title()))
language_choices = tuple(language_choices)


class Repository(models.Model):
    url = models.URLField(blank=True, null=True)
    file = models.FileField(blank=True, null=True)
    translated = models.FileField(blank=True, null=True)
    language = models.CharField(max_length=5, choices=language_choices)
    directory = models.CharField(blank=True, null=True, max_length=512)

    class Meta:
        verbose_name_plural = "Repositories"
Example #19
0
def get_language_codes():
    lang_dict = {val.title(): key for key, val in LANGUAGES.items()}
    return lang_dict
Example #20
0
def get_lang_code(lang: str):
    # setup a dictionary to change requested languagues into langcodes
    Langcodes = dict(map(reversed, LANGUAGES.items()))
    # return the code of the requested language
    return (Langcodes[lang])
Example #21
0
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Sep 19 15:10:09 2020

@author: aaronwright
"""

# Import Google Translate library
from googletrans import Translator, LANGUAGES

# Flip keys and values in list of supported languages.
# Add all languages to seperate list for printing.
LANGUAGES = {v:k for k, v in LANGUAGES.items()}
languages_list = [k for k, v in LANGUAGES.items()]

# Create translate object
translate = Translator()

# Function to translate the text to english.
def translate_text(language, string): 
    try:
        # Use languages dictionary to find language, and translate the string.
        result = translate.translate(string, dest=LANGUAGES[language.lower()]) 
        print(f'In {language.capitalize()}, "{result.origin}" is written "{result.text}".') 
    except:
        print("There was an error. Try running script again.")
       
# Function to gather information from user.
def gather_input():
    while True: 
Example #22
0
# pip install googletrans==3.1.0a0 other versions are f****d
import argparse
import cv2
import pytesseract
from googletrans import Translator, LANGUAGES
from typing import List, Dict, Set
from stringcolor import cs

translator: Translator = Translator(service_urls=['translate.googleapis.com'])

language_abbreviations: Dict[str, str] = {}
abbreviation_set: Set[str] = set()

for abbreviation, language in LANGUAGES.items():
    abbreviation_set.add(abbreviation)
    language_abbreviations[language] = abbreviation


def parse_file(file_path: str, input_language: str, output_language) -> None:
    None
    try:
        file = open(file_path, "r")

        for line in file:
            line = line.strip()

            if not line:
                continue

            print_translation(translate(line, input_langauge, output_language))
Example #23
0
from googletrans import Translator, LANGUAGES
from collections import namedtuple

LANGCODES = dict(map(reversed, LANGUAGES.items()))

# Defining basic structure for translation representation.
Translation = namedtuple('Translation', ['word', 'translations', 'examples'])
Translation_for_render = namedtuple(
    'Translation', ['word', 'translations', 'trigger', 'examples'])


def translate(word, language, render=False):
    """
        Translate word from input language to russian.
        Render argument defines special output format, which is
        convenient to be used in dropdown menu.
    """
    translator = Translator()
    # Select language code
    lang = "auto" if language == "guess" else LANGCODES[language]
    raw_translation = translator.translate(word, dest="ru", src=lang)
    json_data = raw_translation.extra_data
    all_translations = []
    all_examples = []
    try:
        for word_type in json_data["all-translations"]:
            all_translations.extend(word_type[1])
    # Translation does not exists
    except IndexError:
        print(1, json_data)
        return None
Example #24
0
File: deal.py Project: nicbh/mqqbot
def onQQMessage(bot, contact, member, content):
    if bot.isMe(contact, member):
        return
    if content == '' or content == '/表情':
        return
    anic = '@{} '.format(nic)
    if anic in content:
        content = '[@ME] ' + content.replace(anic, '')

    # TODO config file
    if '@ME' in content or member is None:
        if member is not None:
            content = content[5:].strip()
        # look for
        if content == '状态':
            send(bot, contact, '我在哦')
            return
        if content == '黄漫' or content.lower() == 'hentai':
            hhentai = [
                'https://hanime.tv', 'http://hentaiplay.net',
                'https://e-hentai.org'
            ]
            send(bot, contact, random.choice(hhentai))
            return
        if content == '黄图':
            hpic = [
                'https://www.pixiv.net', 'http://konachan.com',
                'https://www.tumblr.com', 'https://www.lofter.com'
            ]
            send(bot, contact, random.choice(hpic))
            return
        if content == '黄文' or content == '黄段子':
            hessay = ['https://www.zhihu.com', 'https://weibo.com']
            send(bot, contact, random.choice(hessay))
            return
        if content == '黄网':
            hsite = ['https://www.baidu.com', 'https://pan.baidu.com']
            send(bot, contact, random.choice(hsite))
            return
        if content.lower() == 'av':
            av = [
                'https://javmoo.net', 'https://hpjav.com',
                'https://www.youav.com', 'https://www.pornhub.com',
                'https://www.xvideos.com'
            ]
            send(bot, contact, random.choice(av))
            return
        if content.lower() == 'help':
            help_text = '指令:状态, help, 黄图, 黄文/黄段子, 黄网, av\n' + \
                        'src2dest sourceLanguage 源语言翻译到目标语言\n' + \
                        'detectlang text 语言检测\n' + \
                        'languages 语言缩写列表\n' + \
                        'bt/bt2/btso keyword 磁力搜索\n' + \
                        '(0<len<9)-(all_len<15) 番号搜索'
            send(bot, contact, help_text)
            return

        # translate
        if '2' in content.split()[0]:
            shortLang = {'c': 'zh-cn', 'j': 'ja', 'e': 'en'}
            sourceLang, targetLang = content.split()[0].lower().split('2')
            transcode = '{}2{} '.format(sourceLang, targetLang)
            if content.lower().startswith(transcode):
                text = content[len(transcode):].strip()
                if sourceLang in shortLang:
                    sourceLang = shortLang[sourceLang]
                if targetLang in shortLang:
                    targetLang = shortLang[targetLang]
                if sourceLang in LANGUAGES and targetLang in LANGUAGES and len(
                        text) > 0:
                    send(
                        bot, contact,
                        translator.translate(text, targetLang,
                                             sourceLang).text)
                    return
        if content.lower().startswith('detectlang '):
            text = content[11:].strip()
            if len(text) > 0:
                detected = translator.detect(text)
                send(
                    bot, contact, '{}@{}'.format(LANGUAGES[detected.lang],
                                                 detected.confidence))
                return
        if content.lower() == 'languages':
            langs = sorted([(short, long)
                            for short, long in LANGUAGES.items()],
                           key=lambda x: x[0])
            send(
                bot, contact, ', '.join(
                    ['{}:{}'.format(short, long) for short, long in langs]))
            return

        # bt
        keyword = None
        btmode = None
        if content.lower().startswith('bt'):
            cmd = content.lower().split()[0]
            if cmd == 'bt':
                keyword = content[3:].strip()
                btmode = 'bt'
            elif cmd == 'bt2':
                keyword = content[4:].strip()
                btmode = 'bt2'
            elif cmd == 'btso':
                keyword = content[5:].strip()
                btmode = 'btso'
        else:
            position = content.find('-')
            if 0 < position < 9 and len(content) < 15:
                keyword = content.replace(' ', '')
        if keyword is not None and len(keyword) > 0 and btmode is not None:
            print_flush('[btInfo]: "{}", "{}"'.format(content, keyword))

            def search_bt(bot, contact, keyword, mode):
                def resp2resp(resp):
                    response = []
                    for item in resp:
                        title = '{}.{}'.format(item['num'], item['name'])
                        info = []
                        if 'type' in item:
                            info.append('类型:{}'.format(item['type']))
                        if 'time' in item:
                            info.append('时间:{}'.format(item['time']))
                        if 'volume' in item:
                            info.append('大小:{}'.format(item['volume']))
                        if 'hot' in item:
                            info.append('人气:{}'.format(item['hot']))
                        if 'last' in item:
                            info.append('最近:{}'.format(item['last']))
                        content = '{}'.format(item['magnet'])
                        response.append('{}\n{}\n{}'.format(
                            title, ' '.join(info), content))
                    return response

                try:
                    r = requests.post('http://{}:5000/search_{}'.format(
                        ip, mode),
                                      data={'keyword': keyword},
                                      timeout=60 * 10)
                    print_flush('[btInfo]: "{}", {}'.format(keyword, r.ok))
                    if r.ok:
                        # push_bt_buffer(keyword)
                        data = json.loads(r.text)
                        if len(data) == 0:
                            if mode == 'btso':
                                send(bot, contact,
                                     '{}找不到"{}"的资源哦'.format(mode, keyword))
                            else:
                                send(
                                    bot, contact,
                                    '{}找不到"{}"的资源,正在尝试下一个网站...'.format(
                                        mode, keyword))
                                if mode == 'bt':
                                    mode = 'bt2'
                                else:
                                    mode = 'btso'
                                netcom = threading.Thread(target=search_bt,
                                                          args=(bot, contact,
                                                                keyword, mode))
                                netcom.setDaemon(True)
                                netcom.start()
                            return
                        if mode == 'bt':
                            response = ['相关排序:'] + resp2resp(data[0])
                            send(bot, contact, response)
                            response = ['人气排序:'] + resp2resp(data[1])
                            send(bot, contact, response)
                        else:
                            response = resp2resp(data)
                            send(bot, contact, response)
                    else:
                        send(bot, contact, '搜索"{}"网络错误了哦'.format(keyword))
                except Exception:
                    import traceback
                    traceback.print_exc()
                    send(bot, contact, '搜索"{}"出现异常了哦'.format(keyword))

            if in_bt_buffer(keyword.lower()):
                send(bot, contact, '刚刚才搜过"{}"了哦'.format(keyword.lower()))
                return
            netcom = threading.Thread(target=search_bt,
                                      args=(bot, contact, keyword, btmode))
            netcom.setDaemon(True)
            netcom.start()

        # others
        else:
            send(bot, contact,
                 '嘤嘤嘤' if member is None else '@{} 嘤嘤嘤'.format(member.name))
    else:
        # repeat
        rand = rand_generator.random()
        prob = abs(SnowNLP(content).sentiments - 0.5) / 2
        print_flush(prob)
        if rand < prob or '二' in content:
            send(bot, contact, content + ' 嘤嘤嘤')
from googletrans import Translator, LANGUAGES

langcodes = dict(map(reversed, LANGUAGES.items()))


def translate_text(text, dest_lang, src_lang):
    dest_lang = dest_lang.lower()
    src_lang = src_lang.lower()

    dest_code = langcodes[dest_lang]
    src_code = langcodes[src_lang]

    translator = Translator()
    translated = translator.translate(str(text), dest_code, src_code)
    translation = translated.text
    return translation


def translate_long_text(text, dest_lang, src_lang):
    dest_lang = dest_lang.lower()
    src_lang = src_lang.lower()

    dest_code = langcodes[dest_lang]
    src_code = langcodes[src_lang]

    n = 14900
    text_list = [(text[i:i + n]) for i in range(0, len(text), n)]
    translation_list = list()
    translator = Translator()
    for t in text_list:
        translated = translator.translate(str(t), dest_code, src_code)
Example #26
0
 def langExists(self, lang):
     LANGCODES = dict(map(reversed, LANGUAGES.items()))
     simbols = list(LANGCODES.values())
     return lang in simbols